导出功能的开发

这次需求的特殊性:

  1. 有几个字段是List类型的,需要转换成AAA,BBB,CCC形式
  2. 有几个字段是JSONArray类型的,需要转换成AAA,BBB,CCC形式
  3. 有几个字段是Integer类型的,但是其有自己对应的中文值
  4. 有几个字段是LocalDateTime类型的,需要转换成相应的时间

代码结构如下:

2022-01-07-19-42-41

工具类还是之前的功能类:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

package com.sdstc.tmp.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class EasyExcelUtils {
    public static void writeExcelWithModel(OutputStream outputStream,
                                           List<? extends Object> dataList,
                                           Class<? extends Object> classT,
                                           String sheetName,
                                           WriteHandler... writeHandlers) {

        ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.write(outputStream, classT).sheet(sheetName);

        for (WriteHandler writeHandler : getDefaultWriteHandlerList()) {
            excelWriterSheetBuilder.registerWriteHandler(writeHandler);
        }

        if (null != writeHandlers && writeHandlers.length > 0) {
            for (WriteHandler writeHandler : writeHandlers) {
                excelWriterSheetBuilder.registerWriteHandler(writeHandler);
            }
        }

        // 开始导出
        excelWriterSheetBuilder.doWrite(dataList);
    }

    private static List<WriteHandler> getDefaultWriteHandlerList() {
        List<WriteHandler> writeHandlerList = new ArrayList<>();
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setWrapped(false);
        setBorderStyle(headWriteCellStyle);
        List<WriteCellStyle> contentWriteCellStyleList = new ArrayList<>();
        WriteCellStyle writeCellStyle = new WriteCellStyle();
        setBorderStyle(writeCellStyle);
        contentWriteCellStyleList.add(writeCellStyle);
        writeHandlerList.add(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyleList));
        writeHandlerList.add(new LongestMatchColumnWidthStyleStrategy());
        return writeHandlerList;
    }

    private static void setBorderStyle(WriteCellStyle writeCellStyle) {
        writeCellStyle.setBorderTop(BorderStyle.THIN);
        writeCellStyle.setBorderRight(BorderStyle.THIN);
        writeCellStyle.setBorderBottom(BorderStyle.THIN);
        writeCellStyle.setBorderLeft(BorderStyle.THIN);
        writeCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        writeCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        writeCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        writeCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    }
}

开发了如下的Converts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

package com.sdstc.tmp.common.utils.converters;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

public class IsRecommendConverter implements Converter<Integer> {
    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        throw new RuntimeException("未实现该操作");
    }

    @Override
    public CellData convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        switch (integer) {
            case 0:
                return new CellData("否");
            case 1:
                return new CellData("是");
            default:
                return new CellData("-");
        }
    }
}

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

package com.sdstc.tmp.common.utils.converters;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.util.List;

public class IsTopConverter implements Converter<Integer> {
    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        throw new RuntimeException("未实现该操作");
    }

    @Override
    public CellData convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        switch (integer) {
            case 0:
                return new CellData("否");
            case 1:
                return new CellData("是");
            default:
                return new CellData("-");
        }
    }
}

其他Converter的代码我就不粘贴了


DTO的代码如下

~~~ java

package com.sdstc.tmp.common.dto;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.fastjson.JSONArray;
import com.sdstc.tmp.common.utils.converters.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class TrendModelDataForExportDTO {

    /**
     * 型体号
     */
    @ExcelProperty(value = "型体号", index = 0)
    private String modelNumber;

    /**
     * 配色名称
     */
    @ExcelProperty(value = "配色名称", index = 1)
    private String placeHolder = "配色名称";

    /**
     * 款式类型
     */
    @ExcelProperty(value = "款式类型", index = 2)
    private String shapeTypeAllName;

    /**
     * 适用品牌
     */
    @ExcelProperty(value = "款式类型", index = 3, converter = JSONArrayConverter.class)
    private JSONArray brands;

    /**
     * 工艺(Id转Name后)
     */
    @ExcelProperty(value = "工艺类型", index = 4, converter = ListConverter.class)
    private List<String> crafts2;

    /**
     * 风格(Id转Name后)
     */
    @ExcelProperty(value = "场景风格", index = 5, converter = ListConverter.class)
    private List<String> styles2;

    /**
     * 趋势主题
     */
    @ExcelProperty(value = "趋势主题", index = 6)
    private String theme;

    /**
     * 流行季节
     */
    @ExcelProperty(value = "流行季节", index = 7, converter = JSONArrayConverter.class)
    private JSONArray seasons;

    /**
     * 流行地区(Id转Name后)
     */
    @ExcelProperty(value = "流行地区", index = 8, converter = ListConverter.class)
    private List<String> regions2;

    /**
     * 趋势标签(Id转Name后)
     */
    @ExcelProperty(value = "趋势标签", index = 9, converter = ListConverter.class)
    private List<String> trendTags2;

    /**
     * 设计师Name
     */
    @ExcelProperty(value = "设计师姓名", index = 10)
    private String designerName;


    /**
     * 发布状态(1:未发布,2:已发布)
     */
    @ExcelProperty(value = "是否发布", index = 11, converter = PublishStatusConverter.class)
    private Integer publishStatus;


    /**
     * 是否置顶(0:否,1:是)
     */
    @ExcelProperty(value = "是否置顶首页", index = 12, converter = IsTopConverter.class)
    private Integer isTop;


    /**
     * 是否推荐(0:否,1:是)
     */
    @ExcelProperty(value = "是否设为推荐", index = 13, converter = IsRecommendConverter.class)
    private Integer isRecommend;

    /**
     * 预览次数
     */
    @ExcelProperty(value = "预览次数", index = 14)
    private Integer browseCount;

    /**
     * 搭配次数
     */
    @ExcelProperty(value = "选用次数", index = 15)
    private Integer usedCount;

    /**
     * 发布人员
     */
    @ExcelProperty(value = "发布人员", index = 16)
    private String publisher = "Placeholder";

    /**
     * 发布时间
     */
    @ExcelProperty(value = "发布时间", index = 17, converter = LocalDateTimeConverter.class)
    private LocalDateTime publishTime;
}

测试代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

@Test
void writeExcelWithModel() {

    try (OutputStream os = new FileOutputStream("tmp.xlsx")) {

        PageTrendModelRequest request = new PageTrendModelRequest();
        request.setCurrent(1);
        request.setLimit(100);

        Page<TrendModelData> trendModelDataPage = trendModelService.pageTrendModel("0", "0", request);

        Page<TrendModelDataForExportDTO> trendModelDataForExportDTOPage =
                entityPageToResponseDataPage(trendModelDataPage, TrendModelDataForExportDTO.class);

        // 核心在这儿
        EasyExcelUtils.writeExcelWithModel(os,
                trendModelDataForExportDTOPage.getRecords(),
                TrendModelDataForExportDTO.class,
                "测试");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

最后Controller层代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21

/**
 * 导出
 */
@PostMapping("/trendModel/exportTrendModel")
public ResponseVo<Page<TrendModelData>> exportTrendModel(
        @RequestHeader(APICons.HEADER_TENANT_ID) String tenantId,
        @RequestAttribute(APICons.REQUEST_USER_ID) String userId,
        @RequestBody @Valid PageTrendModelRequest request,
        HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("UTF-8");
    String fileName = URLEncoder.encode("趋势款式", "UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

    return ResponseVo.createSuccessByData(trendModelService.exportTrendModel(tenantId, userId,
            request,
            response.getOutputStream()));
}

参考资料

  1. easyexcel将数据库枚举字段转换成字符串类型(例:1/男,2/女)的解决方法
  2. EasyExcel 自定义LocalDate类型转换器Converter