4

I have an existing xlsx file, on row 1 I have my headlines, what I need to is add new row at 2 and of course shift everything else down, and then add my data to this row. Can you please help me with this?

static void Append() throws EncryptedDocumentException, InvalidFormatException, IOException
{
    InputStream inp = new FileInputStream("C:/workbook.xlsx");

    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);

    Row row = sheet.createRow((short) 2);
    sheet.shiftRows(1, sheet.getLastRowNum()+1, 1, true,true);
    row.createCell(0).setCellValue("A");
    row.createCell(1).setCellValue("B");
    row.createCell(2).setCellValue("This is a string");
    row.createCell(3).setCellValue(true);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("C:/workbook.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

1 Answer 1

3

Indeed the method shiftRows is a good candidate for this need, you simply need to better set the parameters, like this:

...
// Shift of one row all the rows starting from the 3th row
sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, true);
// Create my new 3th row
Row row = sheet.createRow(2);
...
Sign up to request clarification or add additional context in comments.

4 Comments

Exception in thread "main" java.lang.IllegalArgumentException: firstMovedIndex, lastMovedIndex out of order at org.apache.poi.ss.formula.FormulaShifter.<init>(FormulaShifter.java:81) at org.apache.poi.ss.formula.FormulaShifter.createForRowShift(FormulaShifter.java:126) at org.apache.poi.xssf.usermodel.XSSFSheet.shiftRows(XSSFSheet.java:2970) at MainClass.Append(MainClass.java:67) at MainClass.main(MainClass.java:21)
this works with a simple xlsx file, maybe you should provide more info about your file
you should also mention clearly in your question, the problem met
sheet.shiftRows(1, sheet.getLastRowNum(), 1, true,true); Row row = sheet.createRow(1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.