How to merge cells and set value at the same time by using Apache POI?

自闭症网瘾萝莉.ら 提交于 2019-12-10 13:54:28

问题


I want to merge some cells in my excel template file, and then set values in merged cells. Here is my java code. Before I add set value part, it works well on merging cells. But when I just add set value part, it seems like nothing changed even no cells merged. I also try to move set value part after merge cells part, then office remind me repair the output excel file.

What should I do to merge cells and set value at the same time?

for (int sht = 0; sht < 3; sht++) {
    sheet = workbook.getSheetAt(sht);
    row = 1;
    for (Data d : list) {
        // set value part
        cell = sheet.getRow(row).getCell(0);
        cell.setCellValue(d.a);
        cell = sheet.getRow(row).getCell(1);
        cell.setCellValue(d.b);
        cell = sheet.getRow(row).getCell(2);
        cell.setCellValue(d.c);
        // merge cells part
        sheet.addMergedRegion(new CellRangeAddress(row, row + 1, 0, 0));
        sheet.addMergedRegion(new CellRangeAddress(row, row + 1, 1, 1));
        sheet.addMergedRegion(new CellRangeAddress(row, row + 1, 2, 2));
        sheet.addMergedRegion(new CellRangeAddress(row, row + 1, 3, 3));
        //
        row += 2;
    }
}

回答1:


You can setCellValue in excel cell and then merge the cells according to your requirements.

cell = sheet.getRow(row).getCell(0);
cell.setCellValue(d.a);

You can use sheet.addMergedRegion(new CellRangeAddress(rowFrom,rowTo,colFrom,colTo));

example :

sheet.addMergedRegion(new CellRangeAddress(1,1,4,2)); will merge from D2 to F2. 

Remember it is zero based indexing.

for detail refer BusyDeveloper's Guide



来源:https://stackoverflow.com/questions/33228761/how-to-merge-cells-and-set-value-at-the-same-time-by-using-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!