Apache POI 合并单元格

本文介绍如何使用Java操作Excel文件并实现单元格的合并功能,包括设置合并范围及在合并后的单元格中写入数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

合并单元格所使用的方法:
sheet.addMergedRegion( CellRangeAddress  cellRangeAddress  );

CellRangeAddress  对象的构造方法需要传入合并单元格的首行、最后一行、首列、最后一列。
CellRangeAddress cra=new CellRangeAddress(0, 3, 3, 9);

怎样把数据写入合并后的单元格中
  1. 首先要查看你 CellRangeAddress 构造方法的firstcol index
  2. 创建firstcol cell对象
  3. cell 的set 方法写数据
在合并单元格的后一个位置写数据
  1. 查看  CellRangeAddress 构造方法的lastcol index     
  2. 创建lastcol+1  cell
  3. cell 的set方法写数据

以下是demo:

FileOutputStream fos=new FileOutputStream("D:\\13.xls");
		
		Workbook wb=new HSSFWorkbook();
		
		Sheet sheet=wb.createSheet();
		/*
		 * 设定合并单元格区域范围
		 * 	firstRow  0-based
		 * 	lastRow   0-based
		 * 	firstCol  0-based
		 * 	lastCol   0-based
		 */
		CellRangeAddress cra=new CellRangeAddress(0, 3, 3, 9);		
		
		//在sheet里增加合并单元格
		sheet.addMergedRegion(cra);
		
		Row row = sheet.createRow(0);
		
		Cell cell_1 = row.createCell(3);
		
		cell_1.setCellValue("When you're right , no one remembers, when you're wrong ,no one forgets .");
		
		//cell 位置3-9被合并成一个单元格,不管你怎样创建第4个cell还是第5个cell…然后在写数据。都是无法写入的。
		Cell cell_2 = row.createCell(10);
		
		cell_2.setCellValue("what's up ! ");
		
		wb.write(fos);
		
		fos.close();


评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值