POI3.15 老版本 合并单元格时,合并后单元格内容为合并前左上角第一个单元格的文本内容,
可用\n换行,但是要在Style中设置 style.setWrapText(true);
每个单元格的样式要单独设置, 合并后的大单元格会自动去掉中间的边框,只剩下四周边框
package com.dxk.controller;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
public class ExcelExample {
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("sheet1");
Row row1 = sheet.createRow(0);
Row row2 = sheet.createRow(1);
Row row3 = sheet.createRow(2);
for (int i = 0; i < 10; i++) {
Cell cell1 = row1.createCell(i);
cell1.setCellValue("cell1" + i);
Cell cell2 = row2.createCell(i);
cell2.setCellValue("cell2" + i);
Cell cell3 = row3.createCell(i);
cell3.setCellValue("cell3" + i);
}
Font font = wb.createFont();
font.setBold(true);
font.setFontHeightInPoints((short)10);
CellStyle style = wb.createCellStyle();
// style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充样式为前景色
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); // 前景色为黄色
style.setBorderBottom(BorderStyle.THIN); // 下边框线条为实线
style.setBorderTop(BorderStyle.THIN); // 上边框线条为实线
style.setBorderLeft(BorderStyle.THIN); // 左边框线条为实线
style.setBorderRight(BorderStyle.THIN); // 右边框线条为实线
style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 下边框线条颜色为黑色
style.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 上边框线条颜色为黑色
style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 左边框线条颜色为黑色
style.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 右边框线条颜色为黑色
style.setWrapText(true); // 设置单元格文本自动换行
Cell cell1 = sheet.getRow(1).getCell(0);
cell1.setCellStyle(style);
cell1.setCellValue("部门\n名称\n哈哈哈哈哈哈哈");
Cell cell2 = sheet.getRow(2).getCell(0);
cell2.setCellStyle(style);
cell1.setCellValue("111111");
sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0));
sheet.autoSizeColumn(0); // 自适应列宽
FileOutputStream fos = new FileOutputStream("D://output.xlsx");
wb.write(fos);
fos.close();
wb.close();
System.out.println("完成");
}
}