excel文件上传时,总会遇到各种格式的excel文件,对于不同格式,到底应该如何处理呢?
=== 情况一:===
只上传一个sheet,假设第一个,首行不需要传入
此时第二行是标题行,需要从第三行开始读
public void uploadExcel(InputStream inputStream) throws Exception {Workbook workbook = new XSSFWorkbook(inputStream);Sheet sheet = workbook.getSheetAt(0);List<YourDataObject> dataList = new ArrayList<>();for (Row row : sheet) {// 假设第二行是标题行,从第二行开始读取if (row.getRowNum() == 0 ||row.getRowNum() == 1 ) {continue; }YourDataObject data = new YourDataObject();// 假设每行第一个单元格是String类型,第二个是Doubledata.setName(row.getCell(0).getStringCellValue());data.setValue(row.getCell(1).getNumericCellValue());dataList.add(data);}workbook.close();}
如果运行时出现“Cannot get a STRING value from a NUMERIC cell”问题,可采取以下方式:
1.number类型转化为String类型的过程中造成了Cannot get a STRING value from a NUMERIC cell这样的问题,
因此需要在读取excel单元格数据转化之前设置单元格类型为String
//获取单元格
XSSFCell cell = row.getCell(0);
//设置单元格类型
cell.setCellType(CellType.STRING);
//获取单元格数据
String cellValue = cell.getStringCellValue();
2.DataFormatter通过这个方法可以获取任何格式的cell数据
DataFormatter formatter=new DataFormatter();formatter.formatCellValue(sheet.getRow(i).getCell(13));
3.自己动手写一个函数集中处理转换,使用时调用即可。
private static List<String> convertRowValuesToString(Row row) {List<String> cellValues = new ArrayList<>();for (Cell cell : row) {switch (cell.getCellType()) {case STRING:cellValues.add(cell.getStringCellValue());break;case NUMERIC:cellValues.add(String.valueOf(cell.getNumericCellValue()));break;// Add more cases if needed, e.g., BOOLEAN, FORMULA, etc.default:cellValues.add(""); // or handle other types as needed}}return cellValues;}
public static void main(String[] args) throws IOException {File file = new File("path/to/your/excel/file.xlsx");FileInputStream fis = new FileInputStream(file);Workbook workbook = new XSSFWorkbook(fis);Sheet sheet = workbook.getSheetAt(0);for (Row row : sheet) {List<String> cellValues = convertRowValuesToString(row);System.out.println(cellValues);}workbook.close();fis.close();}
=== 情况二:===
…
(其他情况抽时间持续更新中)
参考链接:
链接:https://www.jianshu.com/p/a8b6f4056daa