且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法删除 Excel 工作表的第一行

更新时间:2023-02-06 11:09:19

apache poi 4.0.1 中,shiftRows 不调整单元格的引用.如果第 1 行向上移动,则单元格中的引用仍然是 r="A2", r="B2", ... 但它们必须调整到新行:r="A1", r="B1", ...

In apache poi 4.0.1, the shiftRows does not adjusting references of the cells. If row 1 is shifted up, then reference in the cells remain r="A2", r="B2", ... But they must be adjusted to the new row though: r="A1", r="B1", ...

此错误仅出现在 XSSF(Office Open XML,*.xlsx)中.二进制HSSF(BIFF,*.xls)没有这个问题.

This bug appears in XSSF (Office Open XML, *.xlsx) only. The binary HSSF (BIFF, *.xls) does not have this problem.

示例:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;

class ExcelDeleteShiftRows {

 public static void main(String[] args) throws Exception {

  String filePath = "SAMPLE.xlsx";

  FileInputStream inputStream = new FileInputStream(filePath);
  Workbook workbook = WorkbookFactory.create(inputStream);
  Sheet sheet = workbook.getSheetAt(0);

  int lastNum = sheet.getLastRowNum();
  Row row0 = sheet.getRow(0);
  if (row0 != null) sheet.removeRow(row0);

  sheet.shiftRows(1, lastNum, -1); 
  // After that the sheet is corrupted. The shiftRows does not adjusting references of the cells.
  // If row 1 is shifted up, then reference in the cells remain r="A2", r="B2", ...
  // But they must be adjusted to the new row though: r="A1", r="B1", ...

  // This corrects this. But of course it is unperformant.
  if (sheet instanceof XSSFSheet) {
   for (Row row : sheet) {
    long rRef = ((XSSFRow)row).getCTRow().getR();
    for (Cell cell : row) {
     String cRef = ((XSSFCell)cell).getCTCell().getR();
     ((XSSFCell)cell).getCTCell().setR(cRef.replaceAll("[0-9]", "") + rRef);
    }
   }
  }

  FileOutputStream outputStream = new FileOutputStream(filePath);
  workbook.write(outputStream);
  outputStream.close();
  workbook.close();

 }
}

请向 apache poi 提交错误,以便 apache poi 开发团队直接更正此问题.这个完整的例子加上一个简短的 SAMPLE.xlsx 足够短,可以作为一个例子来说明问题.

Please file a bug to apache poi to get this corrected directly by apache poi developer team. This complete example, together with a short SAMPLE.xlsx is short enough to be placed as an example to show the problem.