在業(yè)務(wù)系統(tǒng)中多少回接觸到Excel解析。在java開發(fā)平臺下選擇 Apache POI是一個(gè)非常明智的選擇,POI提供非常完善API來讀取或?qū)懭隡icrosoft Office Excel。
目前對導(dǎo)入的數(shù)據(jù)都會進(jìn)行二次加工,我們開發(fā)模式就是先把Excel中的內(nèi)容直接原樣導(dǎo)入數(shù)據(jù)庫對應(yīng)的一張數(shù)據(jù)表中,然后再進(jìn)行二次加工。什么是原樣,那就是我們在excle看到是什么樣的,導(dǎo)入的數(shù)據(jù)就是什么樣的,那怎樣實(shí)現(xiàn)呢?
首先考慮到,exce另存為csv,然后在解析csv就可以,excel另存為csv后,如下

似乎這樣就可以了,但用戶上傳的Excel文件通過后臺轉(zhuǎn)換csv文件也麻煩(PS:其實(shí)我都不知道怎么轉(zhuǎn),有知道的朋友還希望能分享下),說好不是用POI的么,那么接下來我們了解下POI中處理Excel的一些信息

從上圖得知,POI類中帶HSSF的是處理03格式的,XSSF是處理07以上格式的,廢話不多說了,先看看原樣輸出的一個(gè)重要角色 DataFormatter,
查閱官方文檔,紅框的地方清楚說明了,就是現(xiàn)實(shí)Excel中的現(xiàn)實(shí)的文本

這里對于公式類型的還需要判斷下,
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 + "行數(shù)據(jù)");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 }
2015-12-04
新聞熱點(diǎn)
疑難解答
圖片精選