17

I am developing a desktop application related to Excel sheets. I have some problems inserting rows between two rows. Is there any possibility to do this in Java using Apache POI?

Workbook wb3=WorkbookFactory.create(new FileInputStream("Book1.xls"));
Sheet sh=wb3.getSheet("sheet1");

//Reading the available rows using (sh.getRow(1))

//Here i need to insert second row (????)

//I have third row here which already exists (sh.getRow(3))

1 Answer 1

36

I have a solution which is working very well:

Workbook wb3=WorkbookFactory.create(new FileInputStream("Book1.xls"));
Sheet sh=wb3.getSheet("sheet1");  
int rows=sh.getLastRowNum();

Shift the number of rows down the sheet.

sh.shiftRows(2,rows,1);   

Here

  • 2 -- Position at which we need to insert row
  • rows -- Total rows
  • 1 -- How many rows we are going to insert

The reason why we are doing the above process is to make an empty row; only then can we create a new row.

Now we shifted the rows, then we can do our stuff

Coding :

sh.createRow(1);

The above code is used to insert a row at the 1st position, as we defined.

Sign up to request clarification or add additional context in comments.

1 Comment

This is shifting the row content but not the row formatting. The formatting stays in place.

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.