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

问题描述

我试图删除的第三行

这是我基于rgettman,狮子座,自必的意见中提出的编辑。谢谢。

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

甚至尤为明显使用Workbook类的工厂,它不承认键入您:

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

belowe你可以找到一个函数,它确实该行去除,它可以在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