Operation Excel using Java POI merge cells

Merged cells Method:
specify four parameters, the start line, the end of the row, starting column, ending column. This area will then be merged.

Region = new new CellRangeAddress CellRangeAddress (the startRow, endRow, startcol, endcol);
sheet.addMergedRegion (Region);
simple example combined:

public class TestExcel {

public static void main(String[] args) throws IOException {

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

HSSFSheet sheet = workbook.createSheet("sheet");

HSSFRow row0 = sheet.createRow(0);
HSSFCell cell_00 = row0.createCell(0);
cell_00.setCellStyle(style);
cell_00.setCellValue("日期");
HSSFCell cell_01 = row0.createCell(1);
cell_01.setCellStyle(style);
cell_01.setCellValue("午别");

HSSFRow row1 = sheet.createRow(1);
HSSFCell cell_10 = row1.createCell(0);
cell_10.setCellStyle(style);
cell_10.setCellValue("20180412");
HSSFCell cell_11 = row1.createCell(1);
cell_11.setCellStyle(style);
cell_11.setCellValue("上午");

HSSFRow row2 = sheet.createRow(2);
HSSFCell cell_21 = row2.createCell(1);
cell_21.setCellStyle(style);
cell_21.setCellValue("下午");

// merge the two lines representing the date (four parameters, namely the start line, the end of the row, starting column, ending column)
// row and column counts are from 0, and the start and end are combined
// here the combined date excel in two rows one row
CellRangeAddress new new CellRangeAddress Region = (. 1, 2, 0, 0);
sheet.addMergedRegion (Region);

File file = new File("E:\\demo.xls");
FileOutputStream fout = new FileOutputStream(file);
workbook.write(fout);
fout.close();
}

}

Operating results, obtained Excel tables are as follows:



Of course, it can also be more complex, as shown below, so you need to calculate the rows and columns

Guess you like

Origin www.cnblogs.com/wjlwo2ni/p/11120096.html