如何使用Apache POI合并单元格并同时设置值? [英] How to merge cells and set value at the same time by using Apache POI?

查看:75
本文介绍了如何使用Apache POI合并单元格并同时设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 excel 模板文件中合并一些单元格,然后在合并的单元格中设置值.这是我的java代码.在我添加 set value part 之前,它适用于合并单元格.但是当我只添加 set value part 时,即使没有合并单元格,似乎也没有任何改变.我也尝试在合并单元格部分之后移动set value part,然后office提醒我修复输出的excel文件.

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;
    }
}

推荐答案

可以在excel单元格中设置CellValue,然后根据需要合并单元格.

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);

您可以使用 sheet.addMergedRegion(new CellRangeAddress(rowFrom,rowTo,colFrom,colTo));

示例:

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

记住它是基于零的索引.

详情请参阅BusyDeveloper's Guide

这篇关于如何使用Apache POI合并单元格并同时设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆