从一个Excel工作表使用Apache POI HSSF移除一行 [英] Removing a row from an Excel sheet with Apache POI HSSF
问题描述
我使用Apache POI HSSF库导入信息到我的应用程序。问题是,这些文件都需要被分析之前,首先去掉一些额外的/空行。
有不是一个 HSSFSheet.removeRow(INT的rowNum)
方法。只有 removeRow(HSSFRow行)
。这样做的问题是它的空行不能被删除。例如:
sheet.removeRow(sheet.getRow(的rowNum));
给出空行空指针异常,因为的getRow()
返回null。
另外,我在论坛上阅读, removeRow()
只删除单元格内容,但该行仍然存在,作为一个空行。
有没有没有,我想删除的行创造了一个全新的表删除行(空与否)的一种方式?
/ **
*通过其索引中删除一行
* @参数表一个Excel工作表
* @参数的rowIndex删除行的0的索引
* /
公共静态无效removeRow(HSSFSheet片,诠释的rowIndex){
INT lastRowNum = sheet.getLastRowNum();
如果(rowIndex位置> = 0&放大器;&放大器; rowIndex位置与所述; lastRowNum){
sheet.shiftRows(rowIndex位置+ 1,lastRowNum,-1);
}
如果(rowIndex位置== lastRowNum){
HSSFRow removingRow = sheet.getRow(rowIndex位置);
如果(removingRow!= NULL){
sheet.removeRow(removingRow);
}
}
}
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.
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) );
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);
}
}
}
这篇关于从一个Excel工作表使用Apache POI HSSF移除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!