问题
I want to delete completly the first row of my Excel sheet. However, everytime I launch my code, it erased totaly my sheet and every row becomes blank.
Thank you in advance for your help.
I know this question has already been processed many times, but none of the solution proposed worked on my case. There is something wrong for sure.
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();
I need the first row of my sheet to be deleted.
回答1:
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", ...
This bug appears in XSSF
(Office Open XML, *.xlsx
) only. The binary HSSF
(BIFF, *.xls
) does not have this problem.
Example:
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();
}
}
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.
来源:https://stackoverflow.com/questions/54197625/impossible-to-delete-first-row-of-excel-sheet