Word文件:
pom:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- word导出  方式:easypoi-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.4.0</version>
</dependency>
<!--注意:word中要使用循环等标签必须单独导入以下依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>

枚举:

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
import lombok.Getter;

/**
* @author zxz
* @date 2022/10/2013:14
*/
@Getter
public enum WordEnum {
TSET_WORD(301, "测试word导出",
"https://awsacloud.oss-cn-shanghai.aliyuncs.com/word/wordModel/%E6%B5%8B%E8%AF%95.docx"),
;
private Integer type;
private String name;
private String templateURL;

public static WordEnum contains(Integer value) {
for (WordEnum type : WordEnum.values()) {
if (type.type.equals(value)) {
return type;
}
}
return null;
}

WordEnum(Integer type, String name, String templateURL) {
this.type = type;
this.name = name;
this.templateURL = templateURL;
}
}

DTO:

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
import cn.hutool.json.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;

/**
* @author zxz
* @date 2022/10/2013:28
*/

@Data
public class ExportWordReq {

@ApiModelProperty(value = "导出类型")
@NotNull(message = "类型不能为空")
private Integer type;

@ApiModelProperty(value = "请求参数")
private JSONObject param;

}
controller层:
import com.awsa.site.controller.Req.word.ExportWordReq;
import com.awsa.site.service.IWordService;
import com.open.capacity.common.common.BaseRes;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
* @author zxz
* @date 2023/4/21 14:58
**/
@RestController
@Slf4j
@RequestMapping("/word")
@Api(tags = "word文件服务")
public class WordController {
@Resource
private IWordService wordService;

@PostMapping("/exportExcel")
@ApiOperation("导出excel")
public BaseRes exportExcel(@RequestBody @Valid ExportWordReq reqEntity) throws Exception {
return wordService.exportWord(reqEntity);
}

}

service层:

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
import cn.afterturn.easypoi.word.WordExportUtil;
import com.awsa.site.controller.Req.word.ExportWordReq;
import com.awsa.site.enums.WordEnum;
import com.awsa.site.service.IWordService;
import com.awsa.site.utils.oss.OssUtil;
import com.open.capacity.common.common.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
* @author zxz
* @date 2023/4/21 14:57
**/
@Service
@Slf4j
public class WordServiceImpl implements IWordService {
@Override
public BaseRes<String> exportWord(ExportWordReq reqEntity) throws Exception {
WordEnum contains = WordEnum.contains(reqEntity.getType());
if (contains == null) {
return BaseRes.Failure(BaseRes.CODE_4001, "导出类型错误");
}
// 读取模板文件并填充数据
String templateUrl = contains.getTemplateURL();
Map<String, Object> parameterMap = getData(reqEntity);
XWPFDocument document = WordExportUtil.exportWord07(templateUrl, parameterMap);

// 将导出结果存储到内存中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
document.write(outputStream);

// 将导出结果上传至OSS
String fileName = "word/" + contains.getName() + "_" + System.currentTimeMillis() + ".docx";
byte[] fileData = outputStream.toByteArray();
OssUtil.ossUploadMediaByteArray(fileName, fileData);

// 释放资源、删除本地临时文件并打印导出成功信息
outputStream.close();
return BaseRes.Success("https://awsacloud.oss-cn-shanghai.aliyuncs.com/" + fileName);
}


/**
* 调用不同接口 查询数据
*
* @param reqEntity
* @return
* @throws Exception
*/
private Map<String, Object> getData(ExportWordReq reqEntity) throws Exception {
try {
switch (reqEntity.getType()) {
case 301:
Map<String, Object> map=new HashMap<>();
map.put("test","1");
map.put("name","tst名称");
return map;
default:
return new HashMap<>();
}
} catch (Exception e) {
log.info("导出数据查询请求异常:{}", reqEntity.toString());
return new HashMap<>();
}
}
}

模板和导出文件:
源模板:
          测试:

         名称:

导出文件:

         测试:1

         名称:tst名称

Excel文件:
pom:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.3</version>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</exclusion>
<exclusion>
<artifactId>poi-ooxml-schemas</artifactId>
<groupId>org.apache.poi</groupId>
</exclusion>
</exclusions>
</dependency>

枚举:

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
import lombok.Getter;

/**
* @author zxz
* @date 2022/10/2013:14
*/
@Getter
public enum ExcelEnum {
TSET_Excel(301, "测试Excel导出",
"https://awsacloud.oss-cn-shanghai.aliyuncs.com/excel/excelModel/%E8%80%83%E5%8B%A4%E7%BB%9F%E8%AE%A1%E5%AF%BC%E5%87%BA%E6%A8%A1%E6%9D%BF.xlsx"),
;

private Integer type;
private String name;
private String templateURL;

public static ExcelEnum contains(Integer value) {
for (WordEnum type : WordEnum.values()) {
if (type.type.equals(value)) {
return type;
}
}
return null;
}

ExcelEnum(Integer type, String name, String templateURL) {
this.type = type;
this.name = name;
this.templateURL = templateURL;
}
}

DTO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import cn.hutool.json.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;

/**
* @author zxz
* @date 2022/10/2013:28
*/

@Data
public class ExportExcelReq {

@ApiModelProperty(value = "导出类型")
@NotNull(message = "类型不能为空")
private Integer type;

@ApiModelProperty(value = "请求参数")
private JSONObject param;

}

controller层:

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
import com.awsa.site.controller.Req.excel.ExportExcelReq;
import com.awsa.site.service.IExcelService;
import com.open.capacity.common.common.BaseRes;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
* @author zxz
* @date 2022/10/2011:25
*/

@RestController
@Slf4j
@RequestMapping("/excel")
@Api(tags = "文档服务")
public class ExcelController {

@Resource
private IExcelService excelService;

@PostMapping("/exportExcel")
@ApiOperation("导出excel")
public BaseRes exportExcel(@RequestBody @Valid ExportExcelReq reqEntity) throws Exception {
return excelService.exportExcel(reqEntity);
}

}

service层:

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
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSONObject;
import com.awsa.site.controller.Req.UserAttendance.ListUserAttendanceReq;
import com.awsa.site.controller.Req.excel.ExportExcelReq;
import com.awsa.site.controller.Res.UserAttendance.UserAttendanceDTORes;
import com.awsa.site.enums.ExcelEnum;
import com.awsa.site.fegin.UserAttendanceFeign;
import com.awsa.site.service.IExcelService;
import com.awsa.site.utils.oss.OssUtil;
import com.open.capacity.common.common.BaseRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
* @author zxz
* @date 2022/10/2013:27
*/

@Service
@Slf4j
public class ExcelServiceImpl implements IExcelService {

@Resource
private UserAttendanceFeign userAttendanceFeign;

@Override
public BaseRes<String> exportExcel(ExportExcelReq reqEntity) throws Exception {
ExcelEnum contains = ExcelEnum.contains(reqEntity.getType());
if (contains == null) {
return BaseRes.Failure(BaseRes.CODE_4001, "导出类型错误");
}
//获取模板
InputStream inputStream = new URL(contains.getTemplateURL()).openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

//获取数据
List data = getData(reqEntity);

//读取模板
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
//获取页
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//单个值的map填充 -> excelWriter.fill(MAP, writeSheet);
//list的列表填充
excelWriter.fill(data, fillConfig, writeSheet);

excelWriter.finish();

//上传oss
String fileName = "excel/" + contains.getName() + "_" + System.currentTimeMillis() + ".xlsx";
OssUtil.ossUploadMediaByteArray(fileName, outputStream.toByteArray());

//关闭流
inputStream.close();
outputStream.close();
return BaseRes.Success("https://awsacloud.oss-cn-shanghai.aliyuncs.com/" + fileName);

}

/**
* 调用不同接口 查询数据
*
* @param reqEntity
* @return
* @throws Exception
*/
private List getData(ExportExcelReq reqEntity) throws Exception {
try {
switch (reqEntity.getType()) {
case 101:
ListUserAttendanceReq listUserAttendanceReq = JSONObject.parseObject(reqEntity.getParam().toString(), ListUserAttendanceReq.class);
List<UserAttendanceDTORes> userAttendanceDTOResList = userAttendanceFeign.listUserAttendance(listUserAttendanceReq).getData();
setNum(userAttendanceDTOResList);
return userAttendanceDTOResList;
default:
return new ArrayList();
}
} catch (Exception e) {
log.info("导出数据查询请求异常:{}", reqEntity.toString());
return new ArrayList();
}
}

/**
* 添加序号 字段num
*
* @param list
* @throws Exception
*/
private void setNum(List<?> list) throws Exception {
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
Class<?> aClass = o.getClass();
Field field = aClass.getDeclaredField("num");
field.setAccessible(true);
field.set(o, i + 1);
}
}

}