如何使用apache poi删除一行

我试图删除第三行

这是我根据rgettman,Leo,zibi的评论编写的。 谢谢。

public class MainTest { public static void main(String[] args) throws IOException { FileInputStream file = new FileInputStream(new File("test.xlsx") ); XSSFWorkbook wb = new XSSFWorkbook(file); XSSFSheet sheet = wb.getSheetAt(0); sheet.removeRow(sheet.getRow(3)); // sheet.shiftRows(3, 3, -1); File outWB = new File("testResult.xlsx"); OutputStream out = new FileOutputStream(outWB); wb.write(out); out.flush(); out.close(); System.exit(0); } } 

但是这会删除一行中的值,但不会删除该行

如果您正在使用XLS文件(而不是XLSX),那么您应该使用HSSFWorkbook。 我刚刚测试了下面的解决方案,一切正常:

  File file = new File(....); FileInputStream fis = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(fis); HSSFSheet sheet = wb.getSheetAt(0); sheet.shiftRows(3, 3, -1); File outWB = new File(.....); OutputStream out = new FileOutputStream(outWB); wb.write(out); out.flush(); out.close(); 

甚至可以使用Workbook工厂,它可以为您识别类型:

  Workbook wb = WorkbookFactory.create(file); Sheet sheet = wb.getSheetAt(0); sheet.shiftRows(3, 3, -1); 

在下面你可以找到一个删除行的函数,它可以在xls和xlsx(tests;)中使用。

 Workbook wb = WorkbookFactory.create(file); Sheet sheet = wb.getSheetAt(0); removeRow(sheet, 2); File outWB = new File(...); OutputStream out = new FileOutputStream(outWB); wb.write(out); out.flush(); out.close(); public static void removeRow(Sheet sheet, int rowIndex) { int lastRowNum = sheet.getLastRowNum(); if (rowIndex >= 0 && rowIndex < lastRowNum) { sheet.shiftRows(rowIndex + 1, lastRowNum, -1); } if (rowIndex == lastRowNum) { Row removingRow = sheet.getRow(rowIndex); if (removingRow != null) { sheet.removeRow(removingRow); } } } 

查看Shift行的定义:

Shifts rows between startRow and endRow n number of rows. If you use a negative number, it will shift rows up. Code ensures that rows don't wrap around. Calls shiftRows(startRow, endRow, n, false, false); Additionally shifts merged regions that are completely defined in these rows (ie. merged 2 cells on a row to be shifted).

 Specified by: shiftRows(...) in Sheet Parameters: startRow the row to start shifting endRow the row to end shifting n the number of rows to shift 

所以为了删除第3行,你需要使用startRow = 3 (基于零的索引,所以基本上它是第四行), endRow = sheet.getLastRowNum()n = -1来移动选定的行,即从第4行到最后一行向上排1行。

尝试更好的特殊functionremoveRow

此外,XSSFWorkbook使用.xlsx扩展名。