本文介绍了如何使用apache poi删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图删除第三行

这是我根据 rgettman、Leo、zibi 的评论所做的编辑.谢谢你.

THIS IS THE EDIT I made based on the comments of rgettman, Leo, zibi. Thank you.

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

}

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

But this deletes values in a row but does not remove the row

推荐答案

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

If you are working with XLS files (not XLSX) then you should use HSSFWorkbook. I just tested the solution below and everything works fine:

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

甚至更好地使用工作簿工厂,它可以为您识别类型:

or even beter use the Workbook factory, which does type recognizing for you:

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

您可以在下面找到一个删除行的函数,它可以在 xls 和 xlsx 中使用(已测试;)).

belowe you can find a function which does the row removal, it could be used both in xls and xlsx (tested;)).

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

这篇关于如何使用apache poi删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 21:38