- 导入maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easy-excel.version}</version>
</dependency>
我这使用的是3.1.5版本
- 对应实体bean对象
@Data
@ContentRowHeight(18)
@HeadRowHeight(25)
@ColumnWidth(20)
public class InspectExport implements Serializable {
private static final long serialVersionUID = -3032057591998811851L;
@ExcelProperty(index = 0, value = "xx单号")
private String inspectNo;
@ExcelProperty(index = 1, value = "状态")
private String inspectStatusValue;
@ExcelProperty(index = 2, value = "xx品名")
private String inspectProduceKind;
@ExcelProperty(index = 3, value = "xx号")
private String inspectZjEquipmentNo;
@ExcelProperty(index = 4, value = "xx米数")
private BigDecimal outMeters;
@ExcelProperty(index = 5, value = "xx米数")
private BigDecimal actualMeters;
@ExcelProperty(index = 6, value = "xx机号")
private String inspectEquipmentNo;
@ExcelProperty(index = 7, value = "xx")
private String inspectUserName;
@ExcelProperty(index = 8, value = "xx工")
private String userName;
@ExcelProperty(index = 9, value = "时间")
@DateTimeFormat(value = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date inspectEndTime;
@ExcelProperty(index = 10, value = "xx")
private String inspectWeftDensity;
@ExcelProperty(index = 11, value = "xx")
private String inspectWeftArrangement;
@ExcelProperty(index = 12, value = "xx")
private String inspectHorseLength;
@ExcelProperty(index = 13, value = "xx")
private String inspectFlawTotalCount;
@ExcelProperty(index = 14, value = "xx")
private String inspectStart;
@ExcelProperty(index = 15, value = "xx")
private String inspectDown;
- 编写controller和相关service 方法
@ApiOperation(value = "导出检验列表")
@GetMapping("/export")
public APIResult<AjaxResult> export(Inspect inspect) {
return success(inspectService.exportInspect(inspect));
}
@Override
public AjaxResult exportInspect(Inspect inspect) {
inspect.setInspectOrgId(SecurityUtils.getLoginUserOrgId());
List<InspectExport> inspectList = baseMapper.selectHllInspectListForExport(inspect);
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 13);
headWriteFont.setBold(true);
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
try {
String fileName = UUID.randomUUID().toString() + "_" + "xxx记录" + ".xlsx";
String downloadPath = HuawenConfig.getDownloadPath() + fileName;
File desc = new File(downloadPath);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
ExcelWriter excelWriter = EasyExcel.write(new FileOutputStream(downloadPath), InspectExport.class).build();
ExcelWriterSheetBuilder builder = EasyExcel.writerSheet("xxx记录")
.registerWriteHandler(horizontalCellStyleStrategy)
.registerWriteHandler(new ExcelFillCellMergeStrategyHandler(1, new int[]{0, 1, 2, 3, 6, 7, 9, 10, 11, 12, 13, 14, 15}));
WriteSheet writeSheet = builder.build();
excelWriter.write(inspectList, writeSheet);
excelWriter.finish();
return AjaxResult.success(fileName);
} catch (Exception e) {
log.error("inspect export error--->{}", e.getMessage());
return AjaxResult.error("xxx记录导出出错:" + e.getMessage());
}
}
自定义列处理的hanlder 该方法循环太多,数据渲染较慢
@Data
public class ExcelFillCellMergeStrategyHandler implements CellWriteHandler {
private int[] needMergeColumnIndex;
private int needMergeRowIndex;
private int ignoreMergeRowIndex;
public ExcelFillCellMergeStrategyHandler() {
}
public ExcelFillCellMergeStrategyHandler(int needMergeRowIndex, int[] needMergeColumnIndex) {
this.needMergeRowIndex = needMergeRowIndex;
this.needMergeColumnIndex = needMergeColumnIndex;
}
public ExcelFillCellMergeStrategyHandler(int needMergeRowIndex, int[] needMergeColumnIndex, int ignoreMergeRowIndex) {
this.needMergeRowIndex = needMergeRowIndex;
this.needMergeColumnIndex = needMergeColumnIndex;
this.ignoreMergeRowIndex = ignoreMergeRowIndex;
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
int curRowIndex = cell.getRowIndex();
int curColIndex = cell.getColumnIndex();
if (curRowIndex > needMergeRowIndex) {
for (int columnIndex : needMergeColumnIndex) {
if (curColIndex == columnIndex) {
mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
break;
}
}
}
}
private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
Row preRow = cell.getSheet().getRow(curRowIndex - 1);
if (preRow == null) {
preRow = writeSheetHolder.getCachedSheet().getRow(curRowIndex - 1);
}
Cell preCell = preRow.getCell(curColIndex);
Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();
if (ignoreMergeRowIndex == curRowIndex - 1) {
return;
}
boolean dataBool = preData.equals(curData);
boolean equals = cell.getRow().getCell(0).getStringCellValue().equals(cell.getSheet().getRow(curRowIndex - 1).getCell(0).getStringCellValue());
if (dataBool && equals) {
Sheet sheet = writeSheetHolder.getSheet();
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);
}
}
}
}
- 自定义处理列合并的handler
推荐使用该方法,主要是重写AbstractMergeStrategy的merge方法
package com.huawen.inspect.handler;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.ArrayList;
import java.util.List;
public class ColumnMergeStrategyHandler extends AbstractMergeStrategy {
private final List<Integer> needMergeCountList;
private final List<Integer> needMergeColumnIndexList;
private Integer rowIndex;
public ColumnMergeStrategyHandler(List<String> dataList, List<Integer> needMergeColumnIndexList) {
this.needMergeCountList = getNeedMergeCountList(dataList);
this.needMergeColumnIndexList = needMergeColumnIndexList;
}
@Override
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
if (null == rowIndex) {
rowIndex = cell.getRowIndex();
}
needMergeColumnIndexList.forEach(targetColumnIndex -> {
if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == targetColumnIndex) {
mergeColumn(sheet, targetColumnIndex);
}
});
}
private void mergeColumn(Sheet sheet, Integer targetColumnIndex) {
int rowCount = rowIndex;
for (Integer count : needMergeCountList) {
if (count == 1) {
rowCount += count;
continue;
}
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1, targetColumnIndex, targetColumnIndex);
sheet.addMergedRegionUnsafe(cellRangeAddress);
rowCount += count;
}
}
private List<Integer> getNeedMergeCountList(List<String> dataList) {
if (CollUtil.isEmpty(dataList)) {
return new ArrayList<>();
}
List<Integer> needMergeCountList = new ArrayList<>();
int count = 1;
for (int i = 1; i < dataList.size(); i++) {
if (dataList.get(i).equals(dataList.get(i - 1))) {
count++;
} else {
needMergeCountList.add(count);
count = 1;
}
}
needMergeCountList.add(count);
return needMergeCountList;
}
}