Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a Row in Excel Using Java Apache POI

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))

like image 959
kark Avatar asked Jan 25 '13 07:01

kark


People also ask

How do I insert rows in Excel Apache POI?

In this step, we get the last row number by using the getLastRowNum() method and shift the rows using the shiftRows() method. This method shifts rows between startRow and lastRow by the size of rowNumber. Finally, we insert the new rows by using the createRow() method: sheet.

How do you insert a row in Excel using Java?

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

How do I insert a row in Excel XLSX?

Simply click a row number to select a row, hold down the Ctrl and Shift keys, and press plus (+). Excel will then add a row above the selected row.


Video Answer


1 Answers

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.

like image 99
kark Avatar answered Oct 25 '22 06:10

kark