这两天在做动态生成excel,学了下POI,还是蛮简单的.但是做项目的时候遇到了一个问题,就是合并单元格后,同一行 后面的列 会覆盖 前面的列的值
还傻傻的发了个帖子http://bbs.csdn.net/topics/390819393
目标:简单的实现合并单元格并且填充值的功能
问题:后面填充的同一行的合并单元格值 会 将 同一行的前一个覆盖,求解惑
下面粘出代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package
real;
import
java.io.FileOutputStream;
import
org.apache.poi.hssf.usermodel.HSSFSheet;
import
org.apache.poi.hssf.usermodel.HSSFWorkbook;
import
org.apache.poi.ss.util.CellRangeAddress;
public
class
Test {
public
static
void
main(String[] args) {
HSSFWorkbook wb =
new
HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
//第一行前三个合并
CellRangeAddress region1 =
new
CellRangeAddress(
0
,
0
,(
short
)
0
,(
short
)
2
);
sheet.addMergedRegion(region1);
sheet.createRow(
0
).createCell(
0
).setCellValue(
"第一行前三个"
);
//第二行前三个合并
CellRangeAddress region2 =
new
CellRangeAddress(
1
,
1
,(
short
)
0
,(
short
)
2
);
sheet.addMergedRegion(region2);
sheet.createRow(
1
).createCell(
0
).setCellValue(
"第二行前三个"
);
//第一行3,4,5合并
CellRangeAddress region3 =
new
CellRangeAddress(
0
,
0
,(
short
)
3
,(
short
)
5
);
sheet.addMergedRegion(region3);
sheet.createRow(
0
).createCell(
3
).setCellValue(
"第一行3,4,5"
);
FileOutputStream fileOut;
try
{
fileOut =
new
FileOutputStream(
"d://workbook.xls"
);
wb.write(fileOut);
fileOut.close();
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
|
我现在显示的效果
我的目标显示效果
后来总算找到问题所在,就是填充值不能再createRow了,因为后面再createRow就会覆盖前面的值,下面贴出实现功能的demo代码
</pre><pre name="code" class="java">
package real; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.util.CellRangeAddress; public class Test { public static void main(String[] args) { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); //第一行前三个合并 HSSFRow row = sheet.createRow(0); row.createCell(0).setCellValue("第一行前三个"); CellRangeAddress region1 = new CellRangeAddress(0,0,(short)0,(short)2); sheet.addMergedRegion(region1); //第二行前三个合并 CellRangeAddress region2 = new CellRangeAddress(1,1,(short)0,(short)2); sheet.addMergedRegion(region2); sheet.createRow(1).createCell(0).setCellValue("第二行前三个"); //第一行3,4,5合并 CellRangeAddress region3 = new CellRangeAddress(0,0,(short)3,(short)5); sheet.addMergedRegion(region3); row.createCell(3).setCellValue("第一行3,4,5"); FileOutputStream fileOut; try { fileOut = new FileOutputStream("d://workbook.xls"); wb.write(fileOut); fileOut.close(); } catch (Exception e) { e.printStackTrace(); } } }