import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
@Component
public class ImportExcelUtil {
/**
* 导入Excel将每行数据存为List<String>
*
* @param file:文件
* @param cellTypes:key:=列数 列下标从0开始
* value:列类型: 0:numeric
* 1:string
* @param requiredCol:必填列
* @return List<List < String>>
*/
public static List<List<String>> importExcel(MultipartFile file, LinkedHashMap<Integer, Integer> cellTypes, List<Integer> requiredCol) throws Exception {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
//存储所有行数据
List<List<String>> rows = new ArrayList<>();
if (xssfSheet != null) {
//从文件第二行开始解析数据
for (int i = 1; i <= xssfSheet.getLastRowNum(); i++) {
XSSFRow xssfRow = xssfSheet.getRow(i);
//本行不为空且列数size不为0
if (xssfRow != null && xssfRow.getPhysicalNumberOfCells() != 0) {
//存储单行数据
List<String> row = new ArrayList<>();
//解析列数据 key;第几列 value:列类型
int blankCellCount = 0;
int cellCount = cellTypes.size();
Integer[] cellNums = new Integer[cellCount];
for (Map.Entry<Integer, Integer> m : cellTypes.entrySet()) {//循环每列
String cellData = null;
Integer cellNum = m.getKey();
Integer cellType = m.getValue();
XSSFCell cell = xssfRow.getCell(cellNum);
//当前单元格不为空
if (cell != null && cell.getCellType() != 3) {
xssfRow.getCell(cellNum).setCellType(cellType);
if (cellType == 0) {//数值型
cellData = String.valueOf(xssfRow.getCell(cellNum).getNumericCellValue()).trim();
}
if (cellType == 1) {//字符串型
cellData = xssfRow.getCell(cellNum).getStringCellValue().trim();
}
row.add(cellData);
} else if (cell != null && cell.getCellType() == 5) {//错误型
throw new Exception((i + 1) + "行" + (cellNum + 1) + "列为错误单元格");
} else if (cell == null || cell.getCellType() == 3) {//空值型
blankCellCount++;
cellNums[blankCellCount - 1] = cellNum;
cellData = "0";
row.add(cellData);
}
}
if (blankCellCount != 0 && blankCellCount != cellCount) {
//存在为空的列且不是所有列都为空,找为空的列判断该列是否是必填列
for (Integer cellNum : cellNums) {
if (requiredCol.size() > 0 && requiredCol.contains(cellNum)) {
row.clear();
throw new Exception("第"+(i + 1) + "行第" + (cellNum + 1) + "列数据错误,必填项不可为空");
} else {
continue;
}
}
//存在为空的列且所有列都为空
} else if (blankCellCount == cellCount) {
row.clear();
}
if (row.size() != 0) {
rows.add(row);
}
}
}
}
return rows;
}
}
原文地址:https://www.cnblogs.com/xiaoyinger/p/12103734.html
时间: 2024-11-05 13:50:17