使用 Apache POI HSSF 从 Excel 工作表中删除行
我正在使用 Apache POi HSSF 库将信息导入到我的应用程序中。问题是文件有一些额外的/空行需要在解析之前首先删除。
没有 HSSFSheet.removeRow( int rowNum )
方法。仅removeRow( HSSFRow row )
。问题是无法删除空行。例如:
sheet.removeRow( sheet.getRow(rowNum) );
由于 getRow()
返回 null,因此在空行上给出 NullPointerException。 另外,正如我在论坛上读到的那样,removeRow()
仅删除单元格内容,但该行仍然作为空行存在。
有没有一种方法可以删除行(空或非空),而无需创建一个没有我要删除的行的全新工作表?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我的特殊情况(它对我有用):
My special case (it worked for me):
这个答案是 AndreAY 答案的扩展,为您提供删除行的完整功能。
This answer is an extension over AndreAY's answer, Giving you complete function on deleting a row.
我试图深入大脑深处寻找一两年前与 POI 相关的经历,但我的第一个问题是:为什么在解析之前需要删除行?为什么不直接捕获
sheet.getRow(rowNum)
调用的 null 结果并继续?I'm trying to reach back into the depths of my brain for my POI-related experience from a year or two ago, but my first question would be: why do the rows need to be removed before parsing? Why don't you just catch the null result from the
sheet.getRow(rowNum)
call and move on?我知道,这是一个 3 年前的问题,但我最近必须解决同样的问题,而且我必须用 C# 来做。这是我在 NPOI、.Net 4.0 中使用的函数
I know, this is a 3 year old question, but I had to solve the same problem recently, and I had to do it in C#. And here is the function I'm using with NPOI, .Net 4.0
类似的东西
应该可以解决问题。
Something along the lines of
should do the trick.
HSSFRow
有一个名为setRowNum(int rowIndex)
的方法。当您必须“删除”一行时,可以将该索引放入
List
中。然后,当您到达下一行非空时,您从该列表中获取一个索引并调用 setRowNum() 来设置它,然后从该列表中删除该索引。 (或者你可以使用队列)The
HSSFRow
has a method calledsetRowNum(int rowIndex)
.When you have to "delete" a row, you put that index in a
List
. Then, when you get to the next row non-empty, you take an index from that list and set it callingsetRowNum()
, and remove the index from that list. (Or you can use a queue)