poi操作Excel 主要通过HSSF,XSSF两种方式。
HSSF只能解析.xls格式的excel文件,XSSF支持.xls与.xlsx两种格式。
功能:
传递一个Excel文件,拿到里面所有的数据,返回一个集合。
Excel中的数据是什么类型,就返回什么类型的数据。
文件:
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.10</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version>
</dependency>
@ApiOperation("导出xlsx数据")
@PostMapping(value = "/import/xlsx",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public JsonResult readFileXlsx(@RequestPart(value = "fileXlsx") MultipartFile fileXlsx) {List<List<Object>> excel = null;try {excel = excel(fileXlsx);return JsonResult.success("数据导出成功", excel);} catch (Exception e) {e.printStackTrace();}return JsonResult.error("获取数据失败");
}// 获取Excel表格的数据,返回一个集合
public static List<List<Object>> excel(MultipartFile fileXlsx) throws Exception {// 读取整个ExcelXSSFWorkbook sheets = new XSSFWorkbook(fileXlsx.getInputStream());// 获取第一个表单SheetXSSFSheet sheetAt = sheets.getSheetAt(0);List<List<Object>> listExcel = new ArrayList<>();// 循环获取每一行数据for (int i = 0; i < sheetAt.getPhysicalNumberOfRows(); i++) {XSSFRow row = sheetAt.getRow(i);// 读取每一格内容List<Object> list = new ArrayList<>();for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {//获取cellXSSFCell cell = row.getCell(index);//获取 cell的类型CellType cellType = cell.getCellType();// 如果是字符串类型,以字符串的形式获取到cellif (CellType.STRING.equals(cellType)){list.add(cell.getStringCellValue());}// 如果是数字类型,以数字的形式获取到cellif (CellType.NUMERIC.equals(cellType)){list.add(cell.getNumericCellValue());}}listExcel.add(list);}return listExcel;
}
说下我之前导出的方式
@ApiOperation("导出xlsx数据2")
@PostMapping(value = "/import2/xlsx2",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public JsonResult readFileXlsx2(@RequestPart(value = "fileXlsx") MultipartFile fileXlsx) {ExcelReader reader = null;List<List<Object>> read = null;try {reader = ExcelUtil.getReader(fileXlsx.getInputStream());read = reader.read(); //可以加参数,表示从哪行开始读return JsonResult.success("读取成功:", read);} catch (IOException e) {e.printStackTrace();}return JsonResult.error("获取数据失败!");}
这种方式有个不好的地方:第一行数据导出来都是字符串类型的。
我猜是这个工具把第一行当成 表头了,而我传入的文件没有表头,里面都是数据,而我的需求是表里面是数字导出来就要是数字。
所以这种方式不满足我现在的需求,如果有表头就可以这样写。