How to delete an entire row from excel using Java Apache POI?

守給你的承諾、 提交于 2020-01-05 05:54:51

问题


I want to delete an entire row from excel,

I have tried removeRow:

XSSFRow rerow = sheet1.getRow(1);
sheet1.removeRow(rerow);

and shiftRows:

int rowIndex = 1;
int lastIntext = sheet1.getLastRowNum();
sheet1.shiftRows(rowIndex+1, lastIntext, -1);

But it is deleting only values in row not the entire row.


回答1:


Even i faced the same problems but figured after a couple of researches and found

There was a bug/or they might have changed the behavior in <version>4.0.0</version> and <version>4.0.1</version> of Apache Poi for

sheet1.shiftRows(rowIndex+1, lastIntext, -1);

Please use

<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.17</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

And use your code much better way to remove you row like this

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

And it worked for me. May be they might update it in next api releases

Thank you if it would have helped you



来源:https://stackoverflow.com/questions/54252684/how-to-delete-an-entire-row-from-excel-using-java-apache-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!