poi导入工具类 (poi版本3.17)
Java7后,在 try{} 代码块中的流 会自动关闭
导入工具类
/**
* 导入excel,解析数据
* @param file file传输excel文件
* @param keyList 表头所对应实体类的key值
* @return
*/
public static String importExcel(MultipartFile file,List<String> keyList){
try{
if(!file.isEmpty()){
List<Map<String,Object>> dataMapList = new ArrayList<>();
XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow titleRow = sheet.getRow(0);
//内容存在的最后一格单元格数量,从0开始
int lastCellNum = titleRow.getLastCellNum();
//内存存在的最后一行数量,从0开始
int lastRowNum = sheet.getLastRowNum();
//excel内容从1开始
for (int a = 1; a < lastRowNum; a++) {
XSSFRow row = sheet.getRow(a);
//key,value形式存储
Map<String, Object> dataMap = new HashMap<>();
for (int b = 0; b < lastCellNum; b++) {
//获取每行单元格
XSSFCell cell = row.getCell(b);
//将cell中的类型转换为String类型
cell.setCellType(CellType.STRING);
//读取excel中value
String cellValue = StringUtils.isNotBlank(cell.getStringCellValue()) ? cell.getStringCellValue().trim() : "";
//key
String key = keyList.get(b);
//存入dataMap中
dataMap.put(key,cellValue);
}
//存入list
dataMapList.add(dataMap);
}
return JSON.toJSONString(dataMapList);
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Controller代码如下
将jsonStr 转为自己所需要的 对象集合数据, 可以根据各位的需求 自行处理
/**
* 导入产品规格信息
* @param attach
* @return
*/
@RequestMapping("/importExcel")
public R importExcel(@RequestParam("file") MultipartFile attach) {
try{
//数据集合
List<String> keyList = Arrays.asList("productName", "model", "power", "isWaterproof", "rotateOrStatic", "color", "isRemoteControl", "schedulingName", "specWeight", "costPrice", "sellingPrice");
//读取完excel数据后 得到的 对象集合
String jsonStr = ExcelUtils.importExcel(attach, keyList);
List<NProductSpecEntity> dataList = JSON.parseArray(jsonStr, NProductSpecEntity.class);
return R.ok().put("dataList",dataList);
}catch (Exception e){
e.printStackTrace();
}finally {
}
return R.error();
}