近期应一个妹子的邀请做一些跟了一些和Word,excel相关的读写研究。需求很简单,就是从excel表格里读取一些白名单,然后在Word表格里找到这些匹配项再做相应的处理。因为每次手动操作很麻烦,所以呢妹子就找到了我,问下我能不能写个程序来做这件事。我一想这玩意儿应该挺简单的啊,肯定有开源的库来读写excel和Word,而且能提高妹子的工作效率,所以就欣然答应下来了。
之后就Google了一番看看有木有什么开源的库可以用,果不其然第一个就是Apache的POI项目,然后去官网看API文档。总的来说这个库使用起来还是蛮方便,下面介绍下读写Word和excel的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
String path = "whitelist.xlsx"; Workbook wb = null; FileInputStream fis = null; try { fis = new FileInputStream(path); wb = WorkbookFactory.create(fis); } catch (EncryptedDocumentException | InvalidFormatException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException("System hault,can't open file:"+path); } //get first sheet Sheet sheet = wb.getSheetAt(0); int first = sheet.getFirstRowNum(); int last = sheet.getLastRowNum(); //traverse rows for(int i=first; i<=last;i++){ //read row data Row row = sheet.getRow(i); if(row == null){ continue; } //read first cell Cell cell = row.getCell(0); if(null == cell){ continue; } //only read STRING & INTEGER String content = null; if(cell.getCellType() == Cell.CELL_TYPE_STRING){ content = cell.getStringCellValue(); }else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){ content = cell.getNumericCellValue() + ""; }else { continue; } //do something... } try { //close stream and workbook wb.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } |
这个只是读取excel的代码,值得一提是由WorkbookFactory创建出来的Workbook是支持xls和xlsx两种格式的文档,开发者不再需要区分是03还是07格式的excel文件,非常方便。然后读取Word文档却不像读取excel这么方便,他有两套API,一个是HWPFDocument只支持03格式的Word(后缀:doc)[……]