You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.7 KiB

package com.dsideal.base.DataEase.Model;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public List<ExcelRow> readXlsxFile(String filePath, List<String> cols) {
List<ExcelRow> rows = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
int rowNum = 0;
for (Row row : sheet) {
List<String> rowData = new ArrayList<>();
for (Cell cell : row) {
rowData.add(getCellValue(cell));
}
if (rowNum == 0) {
// 如果文件中没有列名,可以在这里手动指定
rows.add(new ExcelRow(cols)); // 根据您的实际列名进行修改
rowNum++;
continue;
}
rows.add(new ExcelRow(rowData));
rowNum++;
}
} catch (Exception e) {
e.printStackTrace();
}
return rows;
}
private String getCellValue(Cell cell) {
return switch (cell.getCellType()) {
case STRING -> cell.getStringCellValue();
case NUMERIC -> String.valueOf(cell.getNumericCellValue());
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
case FORMULA -> cell.getCellFormula();
default -> "";
};
}
}