以下代码直接复制粘贴就能直接看见效果(使用 Apache poi 实现 点这里)
- maven 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
- 测试实体类
@Data
public class AttendanceRecordExcelTest {
@ExcelProperty(value = "用户名")
@ApiModelProperty(value = "用户名")
private String userName;
@ExcelProperty(value = "上班打卡时间")
@ApiModelProperty(value = "上班打卡时间")
@DateTimeFormat(value = "yyyy-MM-dd HH:mm:ss")
private Date morningPunch;
@ExcelProperty(value = "拜访时间")
@ApiModelProperty(value = "拜访时间")
@DateTimeFormat(value = "yyyy-MM-dd HH:mm:ss")
private Date visitTime;
@ExcelProperty(value = "拜访客户")
@ApiModelProperty(value = "拜访客户")
private String customer;
@ExcelProperty(value = "拜访备注")
@ApiModelProperty(value = "拜访备注")
private String visitNotes;
@ExcelProperty(value = "下班打卡时间")
@ApiModelProperty(value = "下班打卡时间")
@DateTimeFormat(value = "yyyy-MM-dd HH:mm:ss")
private Date eveningPunch;
public AttendanceRecordExcelTest(String userName, Date morningPunch, Date visitTime, String customer, String visitNotes, Date eveningPunch) {
this.userName = userName;
this.morningPunch = morningPunch;
this.visitTime = visitTime;
this.customer = customer;
this.visitNotes = visitNotes;
this.eveningPunch = eveningPunch;
}
}
- 合并单元格处理器
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class MergeColumnHandler implements RowWriteHandler {
private final Set<Integer> columnsToMerge;
private final boolean mergeAllColumns;
private final Map<Integer, Object> previousValues;
private final Map<Integer, Integer> previousRowIndices;
/**
* 默认构造方法,用于创建一个默认的合并列处理器。
* 默认情况下,所有列都会被合并。
*/
public MergeColumnHandler() {
this.columnsToMerge = new HashSet<>();
this.mergeAllColumns = true;
this.previousValues = new HashMap<>();
this.previousRowIndices = new HashMap<>();
}
/**
* 构造方法,用于创建一个自定义列合并处理器。
*
* @param columnsToMerge 需要合并的列的索引列表。
*/
public MergeColumnHandler(int... columnsToMerge) {
this.columnsToMerge = new HashSet<>();
for (int column : columnsToMerge) {
this.columnsToMerge.add(column);
}
this.mergeAllColumns = false;
this.previousValues = new HashMap<>();
this.previousRowIndices = new HashMap<>();
}
/**
* 在行写入后处理逻辑,用于处理单元格合并。
* 当前方法会在每一行写入完成后被调用,用于检查是否需要合并单元格。
* 合并单元格的条件是:当前列需要合并,且当前值与前一值相同。
*
* @param context 行写入上下文,包含当前行的索引、当前行对象以及相关写入配置。
*/
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
// 获取当前操作的Sheet对象
Sheet sheet = context.getWriteSheetHolder().getSheet();
// 获取当前行索引
int currentRowIndex = context.getRowIndex();
// 获取当前行对象
Row currentRow = context.getRow();
// 遍历当前行的所有单元格
for (Cell cell : currentRow) {
// 获取当前单元格的列索引
int columnIndex = cell.getColumnIndex();
// 如果不合并所有列且当前列不在合并列列表中,则跳过当前列
if (!mergeAllColumns && !columnsToMerge.contains(columnIndex)) {
continue;
}
// 获取当前单元格的值
Object currentValue = getCellValue(cell);
// 如果当前值不为空
if (currentValue != null) {
// 如果当前值与前一值相同,则合并单元格
if (currentValue.equals(previousValues.get(columnIndex))) {
// 合并单元格
mergeCells(sheet, previousRowIndices.get(columnIndex), currentRowIndex, columnIndex);
} else {
// 否则,更新前一值和前一行索引为当前值和当前行索引
previousValues.put(columnIndex, currentValue);
previousRowIndices.put(columnIndex, currentRowIndex);
}
}
}
}
/**
* 合并单元格。
* 本方法用于将指定范围的单元格合并。它首先检查是否存在已经合并的区域起点与指定的起始行和列相同,
* 如果存在,它将调整已合并区域的终点为指定的结束行,然后重新添加这个调整后的合并区域。
* 如果不存在这样的合并区域,则创建一个新的合并区域并添加到工作表中。
*
* @param sheet 工作表对象,表示要操作的工作表。
* @param startRow 合并范围的起始行索引。
* @param endRow 合并范围的结束行索引。
* @param column 合并范围的列索引。
*/
private void mergeCells(Sheet sheet, int startRow, int endRow, int column) {
// 遍历工作表中所有的合并区域
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i);
// 检查当前合并区域是否与指定的起始行和列匹配
if (region.getFirstRow() == startRow && region.getFirstColumn() == column) {
// 如果匹配,移除当前合并区域,以便可以重新设置它的范围
sheet.removeMergedRegion(i);
// 调整合并区域的结束行为指定的结束行
region.setLastRow(endRow);
// 重新添加调整后的合并区域
sheet.addMergedRegion(region);
// 返回,完成合并
return;
}
}
// 如果没有找到匹配的合并区域,则创建一个新的合并区域并添加到工作表中
sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, column, column));
}
/**
* 根据单元格类型获取单元格的值。
* 此方法用于处理不同类型的Excel单元格,根据单元格的类型(字符串、数字、布尔、公式等),
* 返回相应的单元格值。对于日期格式的数值单元格,将返回Date类型,否则返回Double类型。
* 对于字符串、布尔值和公式单元格,直接返回相应的字符串、布尔值或公式。
*
* @param cell 单元格对象,可能为null。
* @return 单元格的值,根据单元格类型返回不同类型的值,如果单元格为null,则返回null。
*/
private Object getCellValue(Cell cell) {
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
return DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue() : cell.getNumericCellValue();
case BOOLEAN:
return cell.getBooleanCellValue();
case FORMULA:
return cell.getCellFormula();
default:
return null;
}
}
}
- 样式处理器
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
public class CenterAlignCellStyleStrategy {
/**
* 获取居中对齐的样式策略。
* 该方法用于创建并返回一个HorizontalCellStyleStrategy实例,该实例配置了单元格的居中对齐样式。
* 无论是全局样式还是头部样式,都设置了水平和垂直居中对齐,以及细边框样式,以实现统一的表格样式效果。
*
* @return HorizontalCellStyleStrategy 居中对齐的样式策略实例。
*/
public static HorizontalCellStyleStrategy getCenterAlignStrategy() {
// 设置全局单元格样式
WriteCellStyle globalCellStyle = new WriteCellStyle();
// 水平居中
globalCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 垂直居中
globalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 是否自动换行
globalCellStyle.setWrapped(true);
// 左边框
globalCellStyle.setBorderLeft(BorderStyle.THIN);
// 上边框
globalCellStyle.setBorderTop(BorderStyle.THIN);
// 右边框
globalCellStyle.setBorderRight(BorderStyle.THIN);
// 下边框
globalCellStyle.setBorderBottom(BorderStyle.THIN);
// 设置头样式
WriteCellStyle headCellStyle = new WriteCellStyle();
headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 可以设置头字体样式、背景色等
headCellStyle.setBorderLeft(BorderStyle.THIN);
headCellStyle.setBorderTop(BorderStyle.THIN);
headCellStyle.setBorderRight(BorderStyle.THIN);
headCellStyle.setBorderBottom(BorderStyle.THIN);
return new HorizontalCellStyleStrategy(globalCellStyle, headCellStyle);
}
}
- main 测试
public static void main(String[] args) {
List<AttendanceRecordExcelTest> processedRecords = new ArrayList<>();
// processedRecords 定义测试数据
processedRecords.add(new AttendanceRecordExcelTest("刘备", new Date(), new Date(), "秦始皇", "统一六国", new Date()));
processedRecords.add(new AttendanceRecordExcelTest("刘备", new Date(), new Date(), "秦始皇", "统一文字", new Date()));
processedRecords.add(new AttendanceRecordExcelTest("关羽", new Date(), new Date(), "曹操", "官渡之战,诛杀颜良,解白马之围,受封汉寿亭侯", new Date()));
processedRecords.add(new AttendanceRecordExcelTest("张飞", new Date(), new Date(), "张郃", "巴西之战败张郃", new Date()));
processedRecords.add(new AttendanceRecordExcelTest("赵云", new Date(), new Date(), "刘备", "单骑救主", new Date()));
processedRecords.add(new AttendanceRecordExcelTest("赵云", new Date(), new Date(), "刘备", "七进七出救阿斗", new Date()));
processedRecords.add(new AttendanceRecordExcelTest("黄忠", new Date(), new Date(), "刘备", "助刘备攻破益州刘璋", new Date()));
String filePath = "F:\\ChromeDownloadLocation\\test3.xlsx";
try (OutputStream out = Files.newOutputStream(Paths.get(filePath))) {
ExcelWriter excelWriter = EasyExcel.write(out, AttendanceRecordExcelTest.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1")
.registerWriteHandler(CenterAlignCellStyleStrategy.getCenterAlignStrategy())
// // 合并所有列
.registerWriteHandler(new MergeColumnHandler())
// // 合并指定列
// .registerWriteHandler(new MergeColumnHandler(0, 1, 3))
.build();
excelWriter.write(processedRecords, writeSheet);
excelWriter.finish();
System.out.println("Processed data exported successfully to " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
-
默认效果
-
指定列合并效果
-
全部列合并效果