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

时间:2019-01-15 11:05:27

标签: java excel apache-poi

我要完全删除Excel工作表的第一行。但是,每次启动代码时,它会完全擦除我的工作表,并且每一行都变为空白。

在此先感谢您的帮助。

我知道这个问题已经被处理了很多次,但是所提出的解决方案都无法解决我的问题。肯定有问题。

String exportPath = "C:\\Users\\User\\Downloads\\export.xlsx";

FileInputStream inputStream = new FileInputStream(new File(exportPath));
Workbook export = WorkbookFactory.create(inputStream);
Sheet exportSheet = export.getSheetAt(0);

int lastNum = exportSheet.getLastRowNum();
exportSheet.removeRow(exportSheet.getRow(0));
exportSheet.shiftRows(1, lastNum, -1);

inputStream.close();
FileOutputStream outputStream = new FileOutputStream(exportPath);
export.write(outputStream);
export.close();
outputStream.close();

我需要删除工作表的第一行。

1 个答案:

答案 0 :(得分:0)

apache poi 4.0.1中,shiftRows不会调整单元格的引用。如果将第1行上移,则单元格中的引用仍为r =“ A2”,r =“ B2”,...,但是必须将它们调整为新行:r =“ A1”,r =“ B1” ,...

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

示例:

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足够短,足以作为示例来说明问题所在。