1. 程式人生 > 實用技巧 >java匯入excel表格資料

java匯入excel表格資料

package com.tt.rhms.sys.controller;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
* @Author xl
* 匯入Excel資料
*/
@RestController
public class DownloadExcel {
@ResponseBody//返回json資料
@RequestMapping(value = "/lz/excelImport", method = RequestMethod.POST)
public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
if (file.isEmpty()) {
return "檔案為空!";
}
try {
//根據路徑獲取這個操作excel的例項
HSSFWorkbook sheets = new HSSFWorkbook(file.getInputStream());
//根據頁面index獲取sheet頁
HSSFSheet sheet = sheets.getSheetAt(0);
//實體類集合
HSSFRow row = null;
//迴圈sesheet頁中資料從第二行開始,第一行是標題
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
//獲取每一行資料
row = sheet.getRow(i);
String id = row.getCell(0).getStringCellValue();
String name = row.getCell(1).getStringCellValue();
String date = row.getCell(2).getStringCellValue();
String age = row.getCell(3).getStringCellValue();
System.out.println(id+""+name+""+date+""+age+"");
//入庫操作
}
} catch (IOException e) {
e.printStackTrace();
return "匯入失敗";
}
return "匯入成功";
}
}
//表格資料

//postman請求