Insert a Row in Excel Using Apache POI

06 May 2023 Balmiki Mandal 0 Core Java

How to Insert a Row in Excel Using Apache POI

Inserting a row into an Excel sheet can be a huge time-saver, especially when dealing with large spreadsheets. Apache POI provides a great way to accomplish this task. Apache POI is an open source library that is used to read, write and manipulate Microsoft Office documents. This tutorial will explain how to insert a row into an Excel spreadsheet using Apache POI.

Step by Step Guide to Insert a Row in Excel Using Apache POI

  1. Create a Workbook Object: The first step is to create a workbook object. This object represents the actual spreadsheet and can be used to manipulate the data inside of it. The following Java code can be used to create a workbook object:

    Workbook workbook = new XSSFWorkbook();
    
  2. Create a Sheet Object: Once the Workbook object has been created, the next step is to create a Sheet object. This object represents the actual sheet within the workbook, and it is where all of the data manipulation takes place. The following Java code can be used to create a Sheet object:

    Sheet sheet = workbook.createSheet("MySheet");
    
  3. Insert the Row: Now that the Sheet object has been created, the next step is to insert the new row into the Excel spreadsheet. The following Java code can be used to insert a new row at the specified index:

    sheet.shiftRows(index, sheet.getLastRowNum(), 1); 
    Row newRow = sheet.createRow(index);
    
  4. Populate the Row with Data: Once the new row has been inserted into the Excel spreadsheet, the next step is to populate the row with data. The following Java code can be used to populate the row with data from an array of values:

    String[] values = {"value1", "value2", "value3"}; 
    for (int i = 0; i < values.length; i++) { 
    	Cell cell = newRow.createCell(i); 
    	cell.setCellValue(values[i]); 
    }
    
  5. Save the Workbook: Once the row has been successfully added to the Excel spreadsheet, the last step is to save the workbook. The following Java code can be used to save the workbook to a file:

    FileOutputStream out = new FileOutputStream("myExcelFile.xlsx"); 
    workbook.write(out); 
    out.close();
    

Using the steps outlined above, you should now be able to successfully insert a new row into an Excel spreadsheet using Apache POI. By taking advantage of Apache POI's powerful API, you can greatly reduce the amount of time it takes to work with large Excel spreadsheets.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.