excel文件在平時工做中用的比較多,許多重複性的工做徹底能夠交給程序來處理(前段時間測試的同時須要1K行的excel表格,看他一點點托實在看不下去了,就問了規則,而後用java作了個小程序。。。) java
POI(http://poi.apache.org/)是apache的一個開源項目,能夠用來解析office文件,除了excel文件,其餘文件倒沒試過,隨便說說excel文件的讀寫操做。 apache
先來看看讀取操做,先建立HSSFWorkbook對象(xls格式),若是是xlsx格式,須要XSSFWorkbook對象,而後獲取工做簿HSSFSheet,而後遍歷工做簿。 小程序
public static void readExcel(File f){ InputStream instream = null; HSSFWorkbook workbook; //POI解析xls文件的工具類,解析xlsx格式的工具類是XHSSFWorkbook try { try{ instream = new FileInputStream(f); workbook = new HSSFWorkbook(instream); HSSFSheet sheet = workbook.getSheetAt(0); for(Row row : sheet){ for(Cell cell : row){ System.out.println(cell.getStringCellValue()); } } }finally{ if(instream!=null){ instream.close(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
再來看寫入操做, 先建立HSSFWorkbook對象,而後creatSheet(),而後creatRow()和creatCell(),最後寫出HSSFWorkbook 工具
public static void writeExcel(File f){ OutputStream outStream = null; HSSFWorkbook workbook ; try{ try{ outStream = new FileOutputStream(f); workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); Row row = null; Cell cell = null; for(int i = 0 ; i < 100 ; i++){ row = sheet.createRow(i); for(int j = 0 ; j < 100 ; j++){ cell = row.createCell(j); cell.setCellValue("第"+String.valueOf(i)+ "行第"+String.valueOf(j)+"列"); } } workbook.write(outStream); }finally{ if(outStream!=null){ outStream.close(); } } }catch(IOException e){} }