如何用Java删除Excel工作表的内容?
如何使用 Java SE 和 Apache POI 删除 Excel 工作簿中 Excel 工作表的内容?
How to delete contents of an Excel sheet in an Excel workbook, using Java SE and Apache POI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
正如前面的评论中提到的,
这段代码向我抛出 ConcurrentModificationException 。所以,我修改了代码并且它工作正常。这是代码:
As mentioned in previous comments
this code throwing ConcurrentModificationException to me. So, I have modified the code and it's working fine. Here is the code:
我发现removeSheetAt/createSheet实际上并不是一个可接受的答案,因为您无法将新工作表放入工作簿中的正确位置而不遇到 WorkSheet.setSheetOrder
我的世界中的此代码片段
会引发
ConcurrentModificationException
我不得不求助于
I've found that removeSheetAt/createSheet isn't really an acceptable answer, because you can't put the new sheet into the correct position in the workbook without running into a bug in WorkSheet.setSheetOrder
This code snippet
in my world throws a
ConcurrentModificationException
I had to resort to
根据您要删除的内容,您可以删除单个单元格或行。
也删除整个工作表迭代所有行并将其删除。
Depending on what contents you want to delete you may remove a single cell or row.
Too erase the complete sheet iterate over all rows and delete it.
我知道这是一个旧线程,但我认为我找到了最好的解决方案
我所做的只是创建一个相同类型的新工作簿并将其保存在我要删除的文件上。
这是代码
I know this is an old thread but I think I found the best solution
What I did was just create a new workbook of the same type and save it over the file that I wanted to delete.
Heres the code
您可能想要使用
HSSFWorkbook.removeSheetAt(index)
。You probably want to use
HSSFWorkbook.removeSheetAt(index)
.我猜这是一个旧线程,但我也得到了 ConcurrentModificationException。基于 VoiceOfUnreason 我发现这是可行的:
I guess it is an old thread but I also get ConcurrentModificationException. Based on VoiceOfUnreason I found this to work:
我还得到了并发修改异常,也使用了更“现代”的方法:
@Thirupathi S 的基于迭代器的解决方案显然有效,但由于我不完全知道它正在创建 Apple 无法读取的 xslx 文件Numbers 和 OSX 预览(可能还有其他软件)。
我怀疑这与迭代器不删除某些内容有关:removeRow 方法的代码比简单的迭代器删除操作复杂得多。
使用带有反向索引的旧式普通 for 循环就像一个魅力:
I also got concurrent modification exception, also using the more "modern" way of doing it :
The iterator based solution from @Thirupathi S apparently worked, but for reasons I don't exactly know it was creating xslx files that were not readable by Apple's Numbers and OSX preview (and probably other softwares too).
I suspect this has something to do with the iterator not removing something: the code of the removeRow method is way more complex than the simple iterator remove operation.
Using old plain for-loop with reversed index worked like a charm :
这个解决方案对我来说效果很好。还要考虑特殊情况,例如工作表是空白的,或者firstRow 和lastRow 之间存在空格。
This solution works fine with me. And also consider special cases, e.g. the sheet is blank, or the spaces between the firstRow and lastRow are present.
我不删除和重新创建工作表的原因是:保持对工作表范围名称的引用有效。
My reason for not deleting and recreating sheet: Keep references to sheet-scoped names working.
其他迭代器方法似乎可以工作,但 Excel 拒绝打开该文件。
这对我有用:
The other iterator methods appeared to work but Excel then refused to open the file.
This one worked for me: