EasyExcel写
基础数据结构
public class MeasureExcelVO implements Serializable {
private static final long serialVersionUID = -35362314781115090L;
@Data
@ApiModel("详情信息")
@HeadRowHeight(20)
@ContentRowHeight(15)
@HeadStyle(fillForegroundColor = 22)
@HeadFontStyle(fontHeightInPoints = 10)
@ContentFontStyle(fontHeightInPoints = 10, fontName = "宋体")
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER)
public static class Table1 implements Serializable {
private static final long serialVersionUID = 7275329823110111145L;
@ColumnWidth(7)
@ExcelProperty(value = {"水期"}, converter = WaterPhaseCoverter.class)
@ApiModelProperty(value = "水期:0电量汇总, 1丰水期, 2平水期, 3枯水期")
private Integer waterPhase;
@ColumnWidth(7)
@ExcelProperty(value = {"月份"})
@ApiModelProperty(value = "月份")
private Integer month;
@ColumnWidth(12)
@ExcelProperty(value = {"预估电量"})
@ApiModelProperty(value = "预估电量")
private BigDecimal forecastElectricity;
public void setMonth(Integer month) {
this.month = month;
if (6 <= month && month <= 10) {
this.waterPhase = 1;
} else if (5 == month || month == 11) {
this.waterPhase = 2;
} else {
this.waterPhase = 3;
}
}
public static class WaterPhaseCoverter implements Converter<Integer> {
@Override
public Class<Integer> supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return null;
}
@Override
public CellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (value.equals(IntUtil.INT_ZERO)) {
return new CellData<>("电量汇总");
} else if (value.equals(IntUtil.INT_ONE)) {
return new CellData<>("丰水期");
} else if (value.equals(IntUtil.INT_TWO)) {
return new CellData<>("平水期");
} else if (value.equals(IntUtil.INT_THREE)) {
return new CellData<>("枯水期");
} else {
return new CellData<>(value + "");
}
}
}
}
public static class CellWriteHandler extends AbstractCellWriteHandler {
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (cell.getRowIndex() == 13 && 2 == cell.getColumnIndex()) {
cell.setCellFormula("=SUM(C2:C13)");
}
}
}
public static class MergeStrategy extends AbstractMergeStrategy {
private Integer conditionFieldIndex;
private String filedName;
private Integer rowSize;
private List<String> datas = new ArrayList<>();
private MergeStrategy() {
}
public MergeStrategy(Integer rowSize, String fieldName) {
this.rowSize = rowSize;
this.filedName = fieldName;
}
public MergeStrategy(Integer rowSize, String fieldName, Integer conditionFieldIndex) {
this.rowSize = rowSize;
this.filedName = fieldName;
this.conditionFieldIndex = conditionFieldIndex;
}
@Override
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
int currentCellIndex = cell.getColumnIndex();
if (null != head && head.getFieldName().equals(filedName)) {
recordData(currentCellIndex, cell);
if (datas.size() >= rowSize) {
mergeFiled(sheet);
}
}
}
private void mergeFiled(Sheet sheet) {
if (CollUtil.isEmpty(datas)) {
return;
}
String[] startData = datas.get(0).split("_");
String startValue = startData[0];
int startRow = Integer.parseInt(startData[1]);
int startColumn = Integer.parseInt(startData[2]);
for (int i = 1; i < datas.size(); i++) {
String[] currData = datas.get(i).split("_");
int currRow = Integer.parseInt(currData[1]);
int currColumn = Integer.parseInt(currData[2]);
if (!StrUtil.equals(startValue, currData[0]) && currRow - startRow > 1) {
sheet.addMergedRegionUnsafe(new CellRangeAddress(startRow, currRow - 1, startColumn, currColumn));
startValue = currData[0];
startRow = currRow;
startColumn = currColumn;
}
else if (!StrUtil.equals(startValue, currData[0]) && currRow - startRow == 1) {
startValue = currData[0];
startRow = currRow;
startColumn = currColumn;
}
if (i == datas.size() - 1 && currRow - startRow > 0) {
sheet.addMergedRegionUnsafe(new CellRangeAddress(startRow, currRow, startColumn, currColumn));
}
}
}
private void recordData(int currentCellIndex, Cell cell) {
String data = cell.toString();
int rowIndex = cell.getRowIndex();
int columnIndex = cell.getColumnIndex();
data = data + "_" + rowIndex + "_" + columnIndex;
if (ObjectUtil.isNotNull(conditionFieldIndex)) {
if (currentCellIndex < conditionFieldIndex) {
throw new BizException("合并的条件列暂未读取到");
}
data = cell.getRow().getCell(conditionFieldIndex) + "_" + data;
}
datas.add(data);
}
}
}
基于实体类的写
public void quoteMeasure(HttpServletResponse response) {
HashMap<Integer, BigDecimal> monthEleMap = new HashMap<>();
for (int mon = 1; mon <= 12; mon++) {
monthEleMap.put(mon, new BigDecimal(mon * 10));
}
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("测算表格", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8'" + fileName + "'.xlsx");
List<MeasureExcelVO.Table1> table1Datas = new ArrayList<>();
for (Map.Entry<Integer, BigDecimal> entry : monthEleMap.entrySet()) {
Integer month = entry.getKey();
BigDecimal ele = entry.getValue();
MeasureExcelVO.Table1 data = new MeasureExcelVO.Table1();
data.setMonth(month);
data.setForecastElectricity(ele);
table1Datas.add(data);
}
{
MeasureExcelVO.Table1 data = new MeasureExcelVO.Table1();
data.setWaterPhase(IntUtil.INT_ZERO);
table1Datas.add(data);
}
EasyExcel.write(response.getOutputStream(), MeasureExcelVO.Table1.class)
.registerWriteHandler(new MeasureExcelVO.MergeStrategy(table1Datas.size(), "waterPhase"))
.registerWriteHandler(new MeasureExcelVO.CellWriteHandler())
.sheet(0,"详情").doWrite(table1Datas);
} catch (Exception e) {
log.error("导出测算表格异常:{}", e.getMessage());
}
}
基于table的写
public void quoteMeasure(HttpServletResponse response) {
HashMap<Integer, BigDecimal> monthEleMap = new HashMap<>();
for (int mon = 1; mon <= 12; mon++) {
monthEleMap.put(mon, new BigDecimal(mon * 10));
}
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("测算表格", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8'" + fileName + "'.xlsx");
List<MeasureExcelVO.Table1> table1Datas = new ArrayList<>();
for (Map.Entry<Integer, BigDecimal> entry : monthEleMap.entrySet()) {
Integer month = entry.getKey();
BigDecimal ele = entry.getValue();
MeasureExcelVO.Table1 data = new MeasureExcelVO.Table1();
data.setMonth(month);
data.setForecastElectricity(ele);
table1Datas.add(data);
}
{
MeasureExcelVO.Table1 data = new MeasureExcelVO.Table1();
data.setWaterPhase(IntUtil.INT_ZERO);
table1Datas.add(data);
}
WriteSheet writeSheet = EasyExcel.writerSheet(0,"详情").build();
WriteTable writeTable = EasyExcel.writerTable(0).head(MeasureExcelVO.Table1.class).needHead(true).build();
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
.registerWriteHandler(new MeasureExcelVO.MergeStrategy(table1Datas.size(), "waterPhase"))
.registerWriteHandler(new MeasureExcelVO.CellWriteHandler())
.build();
excelWriter.write(table1Datas, writeSheet, writeTable);
excelWriter.finish();
} catch (Exception e) {
log.error("导出测算表格异常:{}", e.getMessage());
}
}
导出结果