如何使用apache poi删除excel中的单元格内容

我想删除单元格内容,但保持其风格,但它总是删除样式和内容。 这是我的代码:

private static void RefreshReport(String sheetName, String resultColumn) { try { InputStream inp = new FileInputStream(getExcelFile()); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheet(sheetName); int colResult = getColumnResult(sheet, resultColumn); int rowStart = getRowResult(sheet, resultColumn); int rowEnd = Math.max(20, sheet.getLastRowNum()); for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { Row r = sheet.getRow(rowNum); if (r != null) { Cell cell = r.createCell(colResult); if (cell.getCellType() != Cell.CELL_TYPE_BLANK) { CellStyle cs = wb.createCellStyle(); cs = cell.getCellStyle(); r.removeCell(cell); cell = r.createCell(colResult); cell.setCellStyle(cs); } } } FileOutputStream fileOut = new FileOutputStream(getExcelFile()); wb.write(fileOut); fileOut.close(); inp.close(); } catch (Exception e) { e.printStackTrace(); } } 

任何帮助将是伟大的。

你的方法不工作的原因是,如果行r不是null ,你总是调用createCell 。 这将覆盖已经存在的任何Cell ,包括内容和样式。

你需要做的是调用getCell 。 这将检索该列索引处的Cell (如果存在);如果不存在,则返回null 。 如果存在,你可以像你一样处理Cell

 if (r != null) { Cell cell = r.getCell(colResult); if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) { // rest of your code here 

除了删除/重新创build方法,您可以将单元格types设置为CELL_TYPE_BLANK 。 这将设置内容为空白,但它也将保留当前单元格的单元格样式。 没有必要删除单元格并重新创build它。

 if (cell.getCellType() != Cell.CELL_TYPE_BLANK) { cell.setCellType(Cell.CELL_TYPE_BLANK); }