17
votes

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

1 Answers

36
votes

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.