目的:
java解析 excel 無非就是apache poi 或者 jxl 兩者在使用上其實都差不多,關鍵還是看你自己熟悉那個,用那個!我也是初次接觸jxl 看很多博客說 jxl只適用於處理小數據量 excel,或者說是功能比較單一的,實際上我看了jxl的包,發現其實用
好了,功能還是很強大的。
需要了解:支持 Reads data from Excel 95, 97, 2000, XP, and 2003 workbooks
jxl.read.biff.BiffException: Unable to recognize OLE stream 出現這個錯誤就是excel 2007格式不符合引起的
官網:http://jexcelapi.sourceforge.net/
java doc: http://jxl.sourceforge.net/javadoc/index.html
依賴管理:
<dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency>
UML大綱:
創建簡單的excel:
1 @Test 2 public void testCreateExcel() { 3 try { 4 // 創建xls文件 5 file.createNewFile(); 6 // 2:創建工作簿 7 WritableWorkbook workbook = Workbook.createWorkbook(file); 8 9 // 3:創建sheet,設置第二三四..個sheet,依次類推即可 10 WritableSheet sheet = workbook.createSheet("測試", 0); 11 // 4:設置titles 12 String[] titles = { "編號", "賬號"}; 13 // 5:給第一行設置列名 14 for (int i = 0; i < titles.length; i++) { 15 sheet.addCell(new Label(i, 0, titles[i])); 16 } 17 sheet.setHeader("aa", "cc", "cc"); 18 // 6:模擬數據庫導入數據 注意起始行為1 19 for (int i = 1; i < 100; i++) { 20 //添加編號 21 sheet.addCell(new Label(0, i, new String("編號"+i))); 22 //添加密碼 23 sheet.addCell(new Label(1, i, new String("編號"+i))); 24 } 25 workbook.write(); 26 workbook.close(); 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } catch (RowsExceededException e) { 30 e.printStackTrace(); 31 } catch (WriteException e) { 32 e.printStackTrace(); 33 } 34 }
效果:
簡單讀取Excel:
1 @Test 2 public void testCreateExcel() { 3 try { 4 //1:創建workbook 5 Workbook workbook = Workbook.getWorkbook(file); 6 //2:獲取第一個工作表sheet 7 Sheet sheet = workbook.getSheet(0); 8 //3:讀取數據 9 System.out.println(sheet.getColumns()); 10 System.out.println(sheet.getRows()); 11 //4.自己注意行列關系 12 for (int i = 0; i < sheet.getRows(); i++) { 13 for (int j = 0; j < sheet.getColumns(); j++) { 14 Cell cell = sheet.getCell(j, i); 15 System.out.println(cell.getContents()); 16 } 17 } 18 } catch (BiffException | IOException e) { 19 e.printStackTrace(); 20 } 21 }