2014-02-21 81 views
3

我试图删除第三行如何使用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工作不会删除该行

+0

我希望excel不期待xlsx文件 – Leo

+1

您正在将行3向下移动1.使用负数向上移位。 – rgettman

回答

8

。我只是测试下面的解决方案,一切工作正常:

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); 

belowe你可以找到一个函数,它不排它可以在xls和xlsx(测试;)中使用)。

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); 
     } 
    } 
} 
+0

你可以考虑接受我的答案,如果它可以帮助你:) – zibi

+1

+1谢谢。这工作真棒。不过,我正在使用'xlsx'。你能否修改你的答案到'xlsx'谢谢。 – CHEBURASHKA

+0

您是否尝试过工作簿工厂? – zibi

0

尝试更好的特殊功能removeRow

此外,XSSFWorkbook用的.xlsx推广工作。

1

见移行的defnition:

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 

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