Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

Somehow I manage to create new rows between two rows in an existing excel file. The problem is, some of the formatting were not include along the shifting of the rows.

One of this, is the row that are hide are not relatively go along during the shift. What I mean is(ex.), rows from 20 to 30 is hidden, but when a create new rows the formating still there. The hidden rows must also move during the insertion/creation of new rows, it should be 21 to 31.

Another thing is, the other object in the sheet that are not in the cell. Like the text box are not move along after the new row is created. Its like the position of these object are fixed. But I want it to move, the same thing as I insert a new row or paste row in excel. If there is a function of inserting a new row, please let me know.

This what I have right now, just a snippet from my code.

HSSFWorkbook wb = new HSSFWorkbook(template); //template is the source of file HSSFSheet sheet = wb.getSheet("SAMPLE"); HSSFRow newRow; HSSFCell cellData;  int createNewRowAt = 9; //Add the new row between row 9 and 10  sheet.shiftRows(createNewRowAt, sheet.getLastRowNum(), 1, true, false); newRow = sheet.createRow(createNewRowAt); newRow = sheet.getRow(createNewRowAt); 

If copy and paste of rows is possible that would be big help. But I already ask it here and can't find a solution. So I decided to create a row as an interim solution. I'm done with it but having a problem like this.

Any help will be much appreciated. Thanks!

like image 683
ace Avatar asked Apr 26 '11 03:04

ace


People also ask

How do I add a row in Excel using Apache POI?

getLastRowNum(); sheet. shiftRows(startRow, lastRow, rowNumber, true, true); 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.

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 rows into the same format?

To insert a single row: Right-click the whole row above which you want to insert the new row, and then select Insert Rows. To insert multiple rows: Select the same number of rows above which you want to add new ones. Right-click the selection, and then select Insert Rows.


2 Answers

Helper function to copy rows shamelessly adapted from here

import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.util.CellRangeAddress;  import java.io.FileInputStream; import java.io.FileOutputStream;  public class RowCopy {      public static void main(String[] args) throws Exception{         HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("c:/input.xls"));         HSSFSheet sheet = workbook.getSheet("Sheet1");         copyRow(workbook, sheet, 0, 1);         FileOutputStream out = new FileOutputStream("c:/output.xls");         workbook.write(out);         out.close();     }      private static void copyRow(HSSFWorkbook workbook, HSSFSheet worksheet, int sourceRowNum, int destinationRowNum) {         // Get the source / new row         HSSFRow newRow = worksheet.getRow(destinationRowNum);         HSSFRow sourceRow = worksheet.getRow(sourceRowNum);          // If the row exist in destination, push down all rows by 1 else create a new row         if (newRow != null) {             worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);         } else {             newRow = worksheet.createRow(destinationRowNum);         }          // Loop through source columns to add to new row         for (int i = 0; i < sourceRow.getLastCellNum(); i++) {             // Grab a copy of the old/new cell             HSSFCell oldCell = sourceRow.getCell(i);             HSSFCell newCell = newRow.createCell(i);              // If the old cell is null jump to next cell             if (oldCell == null) {                 newCell = null;                 continue;             }              // Copy style from old cell and apply to new cell             HSSFCellStyle newCellStyle = workbook.createCellStyle();             newCellStyle.cloneStyleFrom(oldCell.getCellStyle());             ;             newCell.setCellStyle(newCellStyle);              // If there is a cell comment, copy             if (oldCell.getCellComment() != null) {                 newCell.setCellComment(oldCell.getCellComment());             }              // If there is a cell hyperlink, copy             if (oldCell.getHyperlink() != null) {                 newCell.setHyperlink(oldCell.getHyperlink());             }              // Set the cell data type             newCell.setCellType(oldCell.getCellType());              // Set the cell data value             switch (oldCell.getCellType()) {                 case Cell.CELL_TYPE_BLANK:                     newCell.setCellValue(oldCell.getStringCellValue());                     break;                 case Cell.CELL_TYPE_BOOLEAN:                     newCell.setCellValue(oldCell.getBooleanCellValue());                     break;                 case Cell.CELL_TYPE_ERROR:                     newCell.setCellErrorValue(oldCell.getErrorCellValue());                     break;                 case Cell.CELL_TYPE_FORMULA:                     newCell.setCellFormula(oldCell.getCellFormula());                     break;                 case Cell.CELL_TYPE_NUMERIC:                     newCell.setCellValue(oldCell.getNumericCellValue());                     break;                 case Cell.CELL_TYPE_STRING:                     newCell.setCellValue(oldCell.getRichStringCellValue());                     break;             }         }          // If there are are any merged regions in the source row, copy to new row         for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {             CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);             if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {                 CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),                         (newRow.getRowNum() +                                 (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow()                                         )),                         cellRangeAddress.getFirstColumn(),                         cellRangeAddress.getLastColumn());                 worksheet.addMergedRegion(newCellRangeAddress);             }         }     } } 
like image 96
qwerty Avatar answered Oct 02 '22 16:10

qwerty


For people who are looking to insert a row between two rows in an existing excel with XSSF (Apache POI), there is already a method "copyRows" implemented in the XSSFSheet.

import org.apache.poi.ss.usermodel.CellCopyPolicy; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.FileOutputStream;  public class App2 throws Exception{     public static void main(String[] args){         XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("input.xlsx"));         XSSFSheet sheet = workbook.getSheet("Sheet1");         sheet.copyRows(0, 2, 3, new CellCopyPolicy());         FileOutputStream out = new FileOutputStream("output.xlsx");         workbook.write(out);         out.close();     } } 
like image 42
krishna Avatar answered Oct 02 '22 17:10

krishna