If you are working with XLS files (not XLSX), you must use the HSSFWorkbook. I just tested the solution below and everything works fine:
File file = new File(....);
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
sheet.shiftRows(3, 3, -1);
File outWB = new File(.....);
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
or even beter use a factory book that recognizes the type for you:
Workbook wb = WorkbookFactory.create(file);
Sheet sheet = wb.getSheetAt(0);
sheet.shiftRows(3, 3, -1);
below you can find a function that deletes a line, it can be used both in xls and xlsx (checked;)).
Workbook wb = WorkbookFactory.create(file);
Sheet sheet = wb.getSheetAt(0);
removeRow(sheet, 2);
File outWB = new File(...);
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
public static void removeRow(Sheet sheet, int rowIndex) {
int lastRowNum = sheet.getLastRowNum();
if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
if (rowIndex == lastRowNum) {
Row removingRow = sheet.getRow(rowIndex);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
}
}
source
share