使用 Apache POI HSSF 从 Excel 工作表中删除一行 [英] Removing a row from an Excel sheet with Apache POI HSSF

查看:70
本文介绍了使用 Apache POI HSSF 从 Excel 工作表中删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Apache POi HSSF 库将信息导入我的应用程序.问题是文件有一些额外/空行,需要在解析前先删除.

I'm using the Apache POi HSSF library to import info into my application. The problem is that the files have some extra/empty rows that need to be removed first before parsing.

没有 HSSFSheet.removeRow( int rowNum ) 方法.只有 removeRow( HSSFRow row ).问题是无法删除空行.例如:

There's not a HSSFSheet.removeRow( int rowNum ) method. Only removeRow( HSSFRow row ). The problem with this it that empty rows can't be removed. For example:

sheet.removeRow( sheet.getRow(rowNum) );

在空行上给出 NullPointerException,因为 getRow() 返回 null.另外,正如我在论坛上看到的那样,removeRow() 只会擦除单元格内容,但该行仍然是空行.

gives a NullPointerException on empty rows because getRow() returns null. Also, as I read on forums, removeRow() only erases the cell contents but the row is still there as an empty row.

有没有办法删除行(空或非空)而不创建一个没有我想要删除的行的全新工作表?

Is there a way of removing rows (empty or not) without creating a whole new sheet without the rows that I want to remove?

推荐答案

 /**
 * Remove a row by its index
 * @param sheet a Excel sheet
 * @param rowIndex a 0 based index of removing row
 */
public static void removeRow(HSSFSheet sheet, int rowIndex) {
    int lastRowNum=sheet.getLastRowNum();
    if(rowIndex>=0&&rowIndex<lastRowNum){
        sheet.shiftRows(rowIndex+1,lastRowNum, -1);
    }
    if(rowIndex==lastRowNum){
        HSSFRow removingRow=sheet.getRow(rowIndex);
        if(removingRow!=null){
            sheet.removeRow(removingRow);
        }
    }
}

这篇关于使用 Apache POI HSSF 从 Excel 工作表中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆