处理结果:把a,b列相同内容的单元格进行合并
引入easyexcel:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.1</version>
</dependency>
示例代码:
public void exportStrategyDetail(User user, StrategyQuery query, HttpServletResponse response) throws IOException {
String sheetName = "合并单元格";
List<Map> strategyDetail = "对应的导出数据集合";
String excelName = sheetName + System.currentTimeMillis();
// 配置响应和输出流
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
try (OutputStream out = response.getOutputStream()) {
// 将数据导出
List<List<Object>> dataList = new ArrayList<>();
for(Map dto : strategyDetail){
Object object = dto.get("children");
List<Map> childrenMaps = (List<Map>) object;
for(Map dto1 : childrenMaps){
Object object1 = dto1.get("children");
List<Map> childrenMaps1 = (List<Map>) object1;
for(Map dto2 : childrenMaps1){
List<Object> list = new ArrayList<>();
list.add(dto.get("a"));
list.add(dto1.get("b"));
list.add(dto2.get("c");
list.add(dto2.get("d"));
list.add(dto2.get("e"));
list.add(dto2.get("f"));
list.add(dto2.get("g"));
dataList.add(list);
}
}
}
ExcelWriterBuilder writerBuilder = EasyExcel.write(out);
// 添加自定义的合并单元格处理器
// 需要合并的列
int[] cols = {0, 1};
// 从第一行后开始合并
int row = 1;
writerBuilder.registerWriteHandler(new MergeCellWriteHandler(row, cols));
List<List<String>> headers = getStrategyDetailHeaders();
// 导出数据
writerBuilder.sheet(sheetName).head(headers).doWrite(dataList);
} catch (Exception e) {
// 处理异常
e.printStackTrace();
throw new IOException("导出Excel文件失败", e);
}
}
private List<List<String>> getStrategyDetailHeaders() {
List<List<String>> headers = new ArrayList<>();
headers.add(generateHeader("a"));
headers.add(generateHeader("b"));
headers.add(generateHeader("c"));
headers.add(generateHeader("d"));
headers.add(generateHeader("e"));
headers.add(generateHeader("f"));
headers.add(generateHeader("g"));
return headers;
}
private List<String> generateHeader(String... titles) {
List<String> header = new ArrayList<>();
for (String title : titles) {
header.add(title);
}
return header;
}
//自定义合并方法:MergeCellWriteHandler
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.List;
public class MergeCellWriteHandler implements CellWriteHandler {
// 要合并的列索引数组
private final int[] mergeColumnIndex;
// 合并开始的行索引
private final int mergeRowIndex;
/**
* 构造函数
*
* @param mergeRowIndex 合并开始的行索引
* @param mergeColumnIndex 要合并的列索引数组
*/
public MergeCellWriteHandler(int mergeRowIndex, int[] mergeColumnIndex) {
this.mergeRowIndex = mergeRowIndex;
this.mergeColumnIndex = mergeColumnIndex;
}
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
// 单元格创建前的处理(这里不需要处理)
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
// 单元格创建后的处理(这里不需要处理)
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
// 当前行索引
int curRowIndex = cell.getRowIndex();
// 当前列索引
int curColIndex = cell.getColumnIndex();
// 如果当前行大于合并开始行且当前列在需要合并的列中
if (curRowIndex > mergeRowIndex && isMergeColumn(curColIndex)) {
// 进行合并操作
mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
}
}
/**
* 检查当前列是否在需要合并的列中
*
* @param curColIndex 当前列索引
* @return 如果是需要合并的列返回true,否则返回false
*/
private boolean isMergeColumn(int curColIndex) {
for (int columnIndex : mergeColumnIndex) {
if (curColIndex == columnIndex) {
return true;
}
}
return false;
}
/**
* 当前单元格向上合并
*
* @param writeSheetHolder 当前工作表持有者
* @param cell 当前单元格
* @param curRowIndex 当前行索引
* @param curColIndex 当前列索引
*/
private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
// 获取当前单元格的数据
Object curData = getCellData(cell);
// 获取前一个单元格的数据
Cell preCell = cell.getSheet().getRow(curRowIndex - 1).getCell(curColIndex);
Object preData = getCellData(preCell);
// 判断当前单元格和前一个单元格的数据以及主键是否相同
if (curData.equals(preData) && isSamePrimaryKey(cell, curRowIndex)) {
// 获取工作表
Sheet sheet = writeSheetHolder.getSheet();
// 合并单元格
mergeCells(sheet, curRowIndex, curColIndex);
}
}
/**
* 获取单元格的数据
*
* @param cell 单元格
* @return 单元格数据
*/
private Object getCellData(Cell cell) {
return cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
}
/**
* 判断当前单元格和前一个单元格的主键是否相同
*
* @param cell 当前单元格
* @param curRowIndex 当前行索引
* @return 如果主键相同返回true,否则返回false
*/
private boolean isSamePrimaryKey(Cell cell, int curRowIndex) {
String currentPrimaryKey = cell.getRow().getCell(0).getStringCellValue();
String previousPrimaryKey = cell.getSheet().getRow(curRowIndex - 1).getCell(0).getStringCellValue();
return currentPrimaryKey.equals(previousPrimaryKey);
}
/**
* 合并单元格
*
* @param sheet 工作表
* @param curRowIndex 当前行索引
* @param curColIndex 当前列索引
*/
private void mergeCells(Sheet sheet, int curRowIndex, int curColIndex) {
// 获取已合并的区域
List<CellRangeAddress> mergeRegions = sheet.getMergedRegions();
boolean isMerged = false;
// 检查前一个单元格是否已经被合并
for (int i = 0; i < mergeRegions.size() && !isMerged; i++) {
CellRangeAddress cellRangeAddr = mergeRegions.get(i);
if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) {
sheet.removeMergedRegion(i);
cellRangeAddr.setLastRow(curRowIndex);
sheet.addMergedRegion(cellRangeAddr);
isMerged = true;
}
}
// 如果前一个单元格未被合并,则新增合并区域
if (!isMerged) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex);
sheet.addMergedRegion(cellRangeAddress);
}
}
}
标签:int,List,EasyExcel,单元格,导出,cell,add,curRowIndex From: https://www.cnblogs.com/wj123bk/p/18442280