在业务系统中多少回接触到Excel解析。在java开发平台下选择 Apache POI是一个非常明智的选择,POI提供非常完善API来读取或写入Microsoft Office Excel。
目前对导入的数据都会进行二次加工,我们开发模式就是先把Excel中的内容直接原样导入数据库对应的一张数据表中,然后再进行二次加工。什么是原样,那就是我们在excle看到是什么样的,导入的数据就是什么样的,那怎样实现呢?
首先考虑到,exce另存为csv,然后在解析csv就可以,excel另存为csv后,如下
似乎这样就可以了,但用户上传的Excel文件通过后台转换csv文件也麻烦(PS:其实我都不知道怎么转,有知道的朋友还希望能分享下),说好不是用POI的么,那么接下来我们了解下POI中处理Excel的一些信息
从上图得知,POI类中带HSSF的是处理03格式的,XSSF是处理07以上格式的,废话不多说了,先看看原样输出的一个重要角色 DataFormatter,
查阅官方文档,红框的地方清楚说明了,就是现实Excel中的现实的文本
这里对于公式类型的还需要判断下,
1 DataFormatter df = new DataFormatter();2 if (cell.getCellType() == cell.CELL_TYPE_FORMULA) {3 FormulaEvaluator formulaEval = wb.getCreationHelper().createFormulaEvaluator();4 value = df.formatCellValue(cell, formulaEval);5 } else {6 value = df.formatCellValue(cell);7 }
所以就这么一句代码,就取得的单元格中显示的值,算是大工搞成。ps:解析Excle的完整代码
1 private ArrayList<String[]> GetExcel(String filename) 2 throws FileNotFoundException, IOException, Exception { 3 File f = new File(filename); 4 ArrayList data = new ArrayList(); 5 if (f.exists()) { 6 InputStream fis = new FileInputStream(f); 7 Workbook wb = WorkbookFactory.create(fis); 8 Sheet fst = wb.getSheetAt(0); 9 int rowcount = fst.getLastRowNum();10 Row headrow = fst.getRow(0);11 int colcount = headrow.getLastCellNum();12 for (int ri = 0; ri <= rowcount; ri++) {13 System.out.println("");14 System.out.println("第" + ri + "行数据");15 String[] colValues = new String[colcount];16 Row row = fst.getRow(ri);17 for (int i = 0; i < colcount; i++) {18 Cell cell = row.getCell(i);19 String value = "";20 if (cell != null) {21 DataFormatter df = new DataFormatter();22 if (cell.getCellType() == cell.CELL_TYPE_FORMULA) {23 FormulaEvaluator formulaEval = wb.getCreationHelper().createFormulaEvaluator();24 value = df.formatCellValue(cell, formulaEval);25 } else {26 value = df.formatCellValue(cell);27 }28 }29 colValues[i] = value;30 System.out.print(colValues[i] + "--");31 }32 data.add(colValues);33 }34 }35 f.delete();36 return data;37 }
View Code
2015-12-04
原标题:poi 输出Excel显示内容
关键词:excel