main
黄海 9 months ago
parent 6e1b58e877
commit 9ef2298098

@ -8,6 +8,54 @@ import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public static String readCell(Cell cell) {
// 根据单元格的类型来读取值
switch (cell.getCellType()) {
case STRING:
// 字符串类型的单元格
return cell.getStringCellValue();
case NUMERIC:
// 数字类型的单元格
if (DateUtil.isCellDateFormatted(cell)) {
// 如果是日期类型的单元格
return cell.getDateCellValue().toString();
} else {
// 判断是否为整数
double value = cell.getNumericCellValue();
if (value == (int) value) {
// 整数
return String.valueOf((int) value);
} else {
// 小数,保留两位小数
value = cell.getNumericCellValue();
return String.format("%.2f", value);
}
}
case FORMULA:
// 公式类型的单元格
cell.setCellType(CellType.NUMERIC); // 将公式计算结果转为数字
if (DateUtil.isCellDateFormatted(cell)) {
// 如果是日期类型的单元格
return cell.getDateCellValue().toString();
} else {
double formulaValue = cell.getNumericCellValue();
if (formulaValue == (int) formulaValue) {
// 整数
return String.valueOf((int) formulaValue);
} else {
// 小数,保留两位小数
double value = cell.getNumericCellValue();
return String.format("%.2f", value);
}
}
// 可以添加其他类型的处理,如 BOOLEAN, ERROR 等
default:
// 其他类型的单元格
return cell.toString();
}
}
public List<ExcelRow> readXlsxFile(String filePath, List<String> cols) {
List<ExcelRow> rows = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filePath);
@ -18,7 +66,7 @@ public class ExcelReader {
for (Row row : sheet) {
List<String> rowData = new ArrayList<>();
for (Cell cell : row) {
rowData.add(getCellValue(cell));
rowData.add(readCell(cell));
}
if (rowNum == 0) {
// 如果文件中没有列名,可以在这里手动指定
@ -35,22 +83,4 @@ public class ExcelReader {
return rows;
}
private String getCellValue(Cell cell) {
String res = "";
switch (cell.getCellType()) {
case STRING:
res = cell.getStringCellValue();
break;
case NUMERIC:
res = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
res = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
res = cell.getCellFormula();
break;
}
return res;
}
}
Loading…
Cancel
Save