V. Bobrikov
V. Bobrikov

Reputation: 1

Modifying existing xlsx table using apache poi without style/format lose

I need to write data to existing template with formatting stored in it, but styles(font, color, borders) disappear. What I done? load table and get sheet in it:

Workbook xlsxWorkbook = WorkbookFactory.create(new File(filename));
xlsxWorkbook.getSheet(sheetname);

modify like this:

while (condition) {
    Row dataRow = xlsxSheet.getRow(rowIndex);
    if (dataRow == null) {
        dataRow = xlsxSheet.createRow(rowIndex);
    }
    rowIndex++;
    int colIndex = 0;

    for (String colName : colNames) {
        Cell tmp = dataRow.getCell(colIndex);
        if (tmp == null)
            tmp = dataRow.createCell(colIndex);

        tmp.setCellValue(value);

        colIndex++;
    }
}

write back to file:

write(params.getProperty("xlsx-filename"), xlsxSheet.getWorkbook());

What I know about this? Earlier I using same without null check, in that case all styles disappear. Now, if cell and row are not null(not recreated in java code), format saves, but cases when they pre initialized are very different. sometimes data initialize it, sometimes not, sometimes cells with specifically established style are pre initialized.

p.s. sorry for my eng

Upvotes: 0

Views: 1130

Answers (1)

krezus
krezus

Reputation: 1451

As far as i understand, you would like to protect cell style whether you add new row or modify existing row. In order to implement both of them, you can get style of each cell or complete row and set new or modified one.

Row dataRow = xlsxSheet.getRow(rowIndex);
CellStyle  currentRowStyle = dataRow .getRowStyle()
Cell tmp = dataRow.getCell(colIndex);
CellStyle currentStyle = tmp.getCellStyle();

if you want to add new row, you can get the last row number with this instead of checking for null value:

int rowCount = sheet.getLastRowNum();

Upvotes: 1

Related Questions