Merge cells having the same value in excel Java

3.4k views Asked by At

I generated excel document from Postgres database, using POI API. The first column "Ordre" have many same values. However i want to merge this cells having the same values.

I want follow this algorithm :

  • loop through the field "ordre"
  • put a condition if cell(i) = cell(i+1)
  • than merge them

But i have a problem with a condition how to say that (cell(i) = cell(i+1)) in Java, i'm not keen if it can give some satisfactory result i started to write this code :

for (i=3; i<= sheet1.getPhysicalNumberOfRows()  ; i++) {
  Cell cell = sheet1.getRow(i).getCell(0);

 if (sheet1.getRow(i).getCell(0).getStringCellValue() == sheet1.getRow(i+1).getCell(0).getStringCellValue())
  {
    CellRangeAddress cellRangeAddress = new CellRangeAddress(i,i+1,0,0);
    sheet1.addMergedRegion(cellRangeAddress);
  }
}

Any suggestion will be appreciated

2

There are 2 answers

1
sreenath On

use

sheet1.getRow(i).getCell(0).toString().equals(sheet1.getRow(i+1).getCell(0).toString()).

Example:

 for (i=3; i<= sheet1.getPhysicalNumberOfRows()  ; i++) {
 Cell cell = sheet1.getRow(i).getCell(0);

  if (sheet1.getRow(i).getCell(0).toString().equals( sheet1.getRow(i+1).getCell(0).toString()))
  {
    CellRangeAddress cellRangeAddress = new CellRangeAddress(i,i+1,0,0);
    sheet1.addMergedRegion(cellRangeAddress);
  }
}

"==" is for reference equality check. equals() method will be used to check contents equality.

0
Lady Bird On

I had a similar requirement where my first column has repeating values. I tried the below code and it worked fine. Here, I am merging the rows based on the values in the first column. NON_REPTNG_COLS is the number of columns which are to be merged. You can modify this method to suit your requirement.

    int first = 1;
    int last = 1;
    int i = 1;
    while (i < spreadsheet.getPhysicalNumberOfRows()) {
        first = i;
        last = i;
        for (int j = i + 1; j < spreadsheet.getPhysicalNumberOfRows(); j++) {
            if (spreadsheet.getRow(i).getCell(0).toString()
                    .equals(spreadsheet.getRow(j).getCell(0).toString())) {
                last = j;
            }
        }

        for (int k = 0; k < NON_REPTNG_COLS; k++) {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(first,
                    last, k, k);
            spreadsheet.addMergedRegion(cellRangeAddress);
        }
        i = last + 1;
    }