使用poi读写excel、向excel追加数据等,包括.xls和.xlsx文档
1、使用maven引入jar包
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency>
实际引入的jar包为:
如果不使用maven方法引入jar包只需导入以下jar包
2、 向excel追加数据示例:
public static void dealExcel(String in, String out) throws Exception { if (!in.equals(out)) { copyFile(in, out); } FileInputStream input = new FileInputStream(new File(out)); Workbook wb = WorkbookFactory.create(input); System.out.println(wb.getClass()); FileOutputStream output = new FileOutputStream(new File(out)); Sheet sheet = wb.getSheetAt(0); int columnCount = -1; int rowCount = 0; for (Row row : sheet) { if (columnCount == -1) { columnCount = row.getLastCellNum(); } if (row.getLastCellNum() == columnCount) { //增加列 Cell last = row.createCell(columnCount); if (rowCount == 0) { last.setCellValue("Test"); } else { last.setCellValue(rowCount); } rowCount++; } } ////添加行 //Row row = sheet.createRow(sheet.getLastRowNum()); //Cell cell = row.createCell(0); //cell.setCellValue("Test"); output.flush(); wb.write(output); wb.close(); output.close(); }
public static void copyFile(String in, String out) throws Exception { InputStream inputStream = new FileInputStream(new File(in)); File copy = new File(out); if (copy.exists()) { copy.delete(); } copy.createNewFile(); OutputStream outputStream = new FileOutputStream(copy); byte[] buffer = new byte[1024 * 4]; while ((inputStream.read(buffer)) != -1) { outputStream.write(buffer); } inputStream.close(); outputStream.close(); }
3、获取excel数据
public static String getCellData(Cell cell) { Object value = null; CellType cellType = cell.getCellTypeEnum(); if (cellType == CellType.STRING) { value = cell.getStringCellValue(); } else if (cellType == CellType.BOOLEAN) { value = cell.getBooleanCellValue(); } else if (cellType == CellType.NUMERIC) { value = cell.getNumericCellValue(); } else if (cellType == CellType.FORMULA) { value = cell.getCellFormula(); } else if (cellType == CellType.BLANK || cellType == CellType.ERROR) { value = "error"; } else { value = ""; } return String.valueOf(value); }