如何用Java删除Excel工作表的内容?

发布于 2024-11-27 14:21:02 字数 60 浏览 3 评论 0原文

如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

音盲 2024-12-04 14:21:02

正如前面的评论中提到的,

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

这段代码向我抛出 ConcurrentModificationException 。所以,我修改了代码并且它工作正常。这是代码:

Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIte =  sheet.iterator();
while(rowIte.hasNext()){
    rowIte.next();              
    rowIte.remove();
}

As mentioned in previous comments

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

this code throwing ConcurrentModificationException to me. So, I have modified the code and it's working fine. Here is the code:

Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIte =  sheet.iterator();
while(rowIte.hasNext()){
    rowIte.next();              
    rowIte.remove();
}
明天过后 2024-12-04 14:21:02

我发现removeSheetAt/createSheet实际上并不是一个可接受的答案,因为您无法将新工作表放入工作簿中的正确位置而不遇到 WorkSheet.setSheetOrder

我的世界中的此代码片段

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

会引发 ConcurrentModificationException

我不得不求助于

    for (int index = crnt.getLastRowNum(); index >= crnt.getFirstRowNum(); index--) {
        crnt.removeRow( crnt.getRow(index));
    }

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

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

in my world throws a ConcurrentModificationException

I had to resort to

    for (int index = crnt.getLastRowNum(); index >= crnt.getFirstRowNum(); index--) {
        crnt.removeRow( crnt.getRow(index));
    }
望她远 2024-12-04 14:21:02

根据您要删除的内容,您可以删除单个单元格或行。

也删除整个工作表迭代所有行并将其删除。

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}

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.

Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
   sheet.removeRow(row);
}
ゃ懵逼小萝莉 2024-12-04 14:21:02

我知道这是一个旧线程,但我认为我找到了最好的解决方案

我所做的只是创建一个相同类型的新工作簿并将其保存在我要删除的文件上。

这是代码

private void clearOldFile(){
    FileOutputStream out = null;
    try{
        oldFile = new XSSFWorkbook();    
        Sheet sheet = oldFile.createSheet("temp data");

        out = new FileOutputStream(AbsolutePathForTempExcelFile);
        oldFile.write(out);
        out.close();

    } catch(Exception e){
        e.printStackTrace();
    }

}

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

private void clearOldFile(){
    FileOutputStream out = null;
    try{
        oldFile = new XSSFWorkbook();    
        Sheet sheet = oldFile.createSheet("temp data");

        out = new FileOutputStream(AbsolutePathForTempExcelFile);
        oldFile.write(out);
        out.close();

    } catch(Exception e){
        e.printStackTrace();
    }

}
思念满溢 2024-12-04 14:21:02

您可能想要使用HSSFWorkbook.removeSheetAt(index)

You probably want to use HSSFWorkbook.removeSheetAt(index).

一场信仰旅途 2024-12-04 14:21:02

我猜这是一个旧线程,但我也得到了 ConcurrentModificationException。基于 VoiceOfUnreason 我发现这是可行的:

        while (xlsSheet.getPhysicalNumberOfRows() > 0) {
          xlsSheet.removeRow(xlsSheet.getRow(xlsSheet.getLastRowNum()));
        }
        if (xlsSheet.getDrawingPatriarch() != null) {
          xlsSheet.getDrawingPatriarch().clear();
        }

I guess it is an old thread but I also get ConcurrentModificationException. Based on VoiceOfUnreason I found this to work:

        while (xlsSheet.getPhysicalNumberOfRows() > 0) {
          xlsSheet.removeRow(xlsSheet.getRow(xlsSheet.getLastRowNum()));
        }
        if (xlsSheet.getDrawingPatriarch() != null) {
          xlsSheet.getDrawingPatriarch().clear();
        }
ま昔日黯然 2024-12-04 14:21:02

我还得到了并发修改异常,也使用了更“现代”的方法:

sheet.forEach(r->sheet.remove(r));

@Thirupathi S 的基于迭代器的解决方案显然有效,但由于我不完全知道它正在创建 Apple 无法读取的 xslx 文件Numbers 和 OSX 预览(可能还有其他软件)。

我怀疑这与迭代器不删除某些内容有关:removeRow 方法的代码比简单的迭代器删除操作复杂得多。

使用带有反向索引的旧式普通 for 循环就像一个魅力:

for (int i = sheet.getLastRowNum(); i >= 0; i--) {
  sheet.removeRow(sheet.getRow(i));
}

I also got concurrent modification exception, also using the more "modern" way of doing it :

sheet.forEach(r->sheet.remove(r));

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 :

for (int i = sheet.getLastRowNum(); i >= 0; i--) {
  sheet.removeRow(sheet.getRow(i));
}
丶视觉 2024-12-04 14:21:02

这个解决方案对我来说效果很好。还要考虑特殊情况,例如工作表是空白的,或者firstRow 和lastRow 之间存在空格。

public void cleanSheet(Sheet sheet) {
    int numberOfRows = sheet.getPhysicalNumberOfRows();

    if(numberOfRows > 0) {
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            if(sheet.getRow(i) != null) {
                sheet.removeRow( sheet.getRow(i));
            } else {
                System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... skip line: " + i);
            }
        }               
    } else {
        System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... is empty");
    }       
}

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.

public void cleanSheet(Sheet sheet) {
    int numberOfRows = sheet.getPhysicalNumberOfRows();

    if(numberOfRows > 0) {
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
            if(sheet.getRow(i) != null) {
                sheet.removeRow( sheet.getRow(i));
            } else {
                System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... skip line: " + i);
            }
        }               
    } else {
        System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... is empty");
    }       
}
蛮可爱 2024-12-04 14:21:02

我不删除和重新创建工作表的原因是:保持对工作表范围名称的引用有效。

for(int i = sheet.getLastRowNum(); i >= 0; i--)
{
  Row row = sheet.getRow(i);
  if(row != null)
  {
    sheet.removeRow(row);
  }
}

My reason for not deleting and recreating sheet: Keep references to sheet-scoped names working.

for(int i = sheet.getLastRowNum(); i >= 0; i--)
{
  Row row = sheet.getRow(i);
  if(row != null)
  {
    sheet.removeRow(row);
  }
}
拒绝两难 2024-12-04 14:21:02

其他迭代器方法似乎可以工作,但 Excel 拒绝打开该文件。
这对我有用:

int rownum;
while ((rownum=sheet.getLastRowNum()) > 0) sheet.removeRow(sheet.getRow(rownum));

The other iterator methods appeared to work but Excel then refused to open the file.
This one worked for me:

int rownum;
while ((rownum=sheet.getLastRowNum()) > 0) sheet.removeRow(sheet.getRow(rownum));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文