Apache POI 合并单元格

合并单元格所使用的方法:
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:

  1. FileOutputStream fos=new FileOutputStream("D:\\13.xls");
  2. Workbook wb=new HSSFWorkbook();
  3. Sheet sheet=wb.createSheet();
  4. /*
  5. * 设定合并单元格区域范围
  6. *  firstRow  0-based
  7. *  lastRow   0-based
  8. *  firstCol  0-based
  9. *  lastCol   0-based
  10. */
  11. CellRangeAddress cra=new CellRangeAddress(0, 3, 3, 9);
  12. //在sheet里增加合并单元格
  13. sheet.addMergedRegion(cra);
  14. Row row = sheet.createRow(0);
  15. Cell cell_1 = row.createCell(3);
  16. cell_1.setCellValue("When you're right , no one remembers, when you're wrong ,no one forgets .");
  17. //cell 位置3-9被合并成一个单元格,不管你怎样创建第4个cell还是第5个cell…然后在写数据。都是无法写入的。
  18. Cell cell_2 = row.createCell(10);
  19. cell_2.setCellValue("what's up ! ");
  20. wb.write(fos);
  21. fos.close();
 
上一篇:李飞飞确认将离职!谷歌云AI总帅换人,卡耐基·梅隆老教授接棒


下一篇:bash快捷建