1、问题描述:最近Java项目中需要用到使用Apache.poi导出文件到excel,用到合并单元格的操作。特此记录一下合并单元格的代码步骤,以及合并后的效果。
2、Demo展示:合并单元格Demo的代码如下所示。
public class Excel2 {
public static void main(String[] args) throws IOException {
FileOutputStream fos=new FileOutputStream("D:\\hebing.xls");
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet();
/*
* 设定合并单元格区域范围
* firstRow 0-based
* lastRow 0-based
* firstCol 0-based
* lastCol 0-based
*/
CellRangeAddress cra=new CellRangeAddress(0, 2, 3, 6);
//在sheet里增加合并单元格
sheet.addMergedRegion(cra);
HSSFRow row = sheet.createRow(0);
HSSFCell cell_1 = row.createCell(3);
cell_1.setCellValue("this is merge unit ");
//cell 位置3-6被合并成一个单元格,不管你怎样创建第4个cell还是第5个cell…然后在写数据。都是无法写入的。
HSSFCell cell_2 = row.createCell(7);
cell_2.setCellValue("what's up ! ");
wb.write(fos);
fos.close();
}
}
3、导出的excel表格
4、合并单元格的关键代码:
//创建合并单元格区域
CellRangeAddress cra=new CellRangeAddress(0, 2, 3, 6);
//在sheet里增加合并单元格
sheet.addMergedRegion(cra);
5、源码解析
/**
* Creates new cell range. Indexes are zero-based.
*
* @param firstRow Index of first row
* @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}
* @param firstCol Index of first column
* @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}
*/
public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {
super(firstRow, lastRow, firstCol, lastCol);
if (lastRow < firstRow || lastCol < firstCol) {
throw new IllegalArgumentException("Invalid cell range, having lastRow < firstRow || lastCol < firstCol, " +
"had rows " + lastRow + " >= " + firstRow + " or cells " + lastCol + " >= " + firstCol);
}
}
创建合并单元格的方法CellRangeAdress(int firstRow,int lastRow,int fitstCol,int lastCol);中的参数四个参数分别表示,合并区域的第一行,最后一行,第一列,最后一列。并且合并区域的单元格数目必须大于2,否则出错。