完整代码
package com.dushanzi.appliance_manage.util;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/*
*获取Excel文件数据的类
* wus
* 2022.10.27
*/
public class ApplianceManageExcelUtil {
public static List<Map<String, Object>> readExcel(String fileUrl, boolean b) throws IOException {
File file = new File(fileUrl);
//获取文件名字
String fileName = file.getName();
//获取文件类型
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
System.out.println("****fileType:" + fileType);
//获取输入流
InputStream stream = new FileInputStream(file);
//获取工作簿
Workbook xssfWorkbook = null;
if (fileType.equals("xlsx")) {
xssfWorkbook = new XSSFWorkbook(stream);
} else {
System.out.println("您输入的excel格式不正确");
}
List<Map<String,Object>> aList = new ArrayList();
// Read the Sheet
Sheet Sheet = xssfWorkbook.getSheetAt(0);
// Read the Row 从0开始
for (int rowNum = 0; rowNum <= Sheet.getLastRowNum(); rowNum++) {
Row Row = Sheet.getRow(rowNum);
if (Row != null) {
//判断这行记录是否存在
if (Row.getLastCellNum() < 1 || "".equals(Row.getCell(0))) {
continue;
}
//获取每一行封装成对象
Map<String,Object> rowList = new HashMap<>();
for (int colNum = 0; colNum < Row.getLastCellNum(); colNum++) {
/*if (Row.getCell(colNum).toString()==null ){
rowList.put(colNum+"","");
continue;
}*/
try{rowList.put(colNum+"", Row.getCell(colNum).toString());
}
catch (Exception e){
e.printStackTrace();
}
}
aList.add(rowList);
}
}
return aList;
}
}
紫色部分是因为获取的excel表格中间有空的列不能获取报空指针异常,所以我加了trycatch捕获一下就好了,实习小白遇到的问题发一下,献丑了哈哈