<!-- poi-tl导出word文档-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
需要的实体类
package com.dream.domain.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Data
public class QuestionVo implements Serializable {
private String quesTitle;
private int type;
private String numb;
private ArrayList<AnwserVo> anwser;
}
package com.dream.domain.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class AnwserVo implements Serializable {
private String content;
private int type;
private int supplementType;
private String supplement;
}
以下是实现逻辑
package com.dream.controller.file;
import com.deepoove.poi.XWPFTemplate;
import com.dream.common.BussinessException;
import com.dream.common.Result;
import com.dream.domain.vo.AnwserVo;
import com.dream.domain.vo.PageVo;
import com.dream.domain.vo.QuestionVo;
import com.dream.domain.vo.Student;
import com.dream.service.admin.QuestionnaireAdminService;
import com.dream.service.admin.UserMangeAdminService;
import com.dream.utils.Utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
@RequestMapping("file")
public class FileUploadController {
private final ResourceLoader resourceLoader;
@Autowired
private QuestionnaireAdminService questionnaireAdminService;
// 通过构造函数注入ResourceLoader
public FileUploadController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* 导出单个word
* @param id
* @param response
*/
@GetMapping("/export")
public void exportStudents(@RequestParam("id") Integer id,HttpServletResponse response) {
try {
// 1. 加载模板文件
Resource resource = resourceLoader.getResource("classpath:templates/question.docx");
// 2. 验证模板是否存在
if (!resource.exists()) {
throw new FileNotFoundException("模板文件未找到");
}
Map<String,ArrayList<QuestionVo>> map1 = questionnaireAdminService.queryUserQuestionnaireById(id);
ArrayList<QuestionVo> list = (ArrayList<QuestionVo>) map1.get("subject");
// 3. 准备数据(示例数据,实际应从数据库获取)
Map<String, String> data = new HashMap<>();
if(list.size() > 0){
Map map = questionnaireAdminService.queryNameByQuestionnaireId(id);
for (int i = 0; i <list.size(); i++) {
QuestionVo questionVo = list.get(i);
List<AnwserVo> anwser = questionVo.getAnwser();
switch (questionVo.getNumb()){
case "one":
for (int j = 0; j <anwser.size(); j++) {
AnwserVo anwserVo = anwser.get(j);
if (anwserVo.getType() == 1){
data.put("one_"+j,"√");
}
}
break;
case "two":
for (int j = 0; j <anwser.size(); j++) {
AnwserVo anwserVo = anwser.get(j);
if (anwserVo.getType() == 1){
data.put("two_"+j,"√");
}
if(anwserVo.getSupplementType() == 1){
data.put("two_supplement",anwserVo.getSupplement());
}
}
break;
case "three":
for (int j = 0; j <anwser.size(); j++) {
AnwserVo anwserVo = anwser.get(j);
if (anwserVo.getType() == 1){
data.put("three_"+j,"√");
}
}
break;
case "four":
for (int j = 0; j <anwser.size(); j++) {
AnwserVo anwserVo = anwser.get(j);
if (anwserVo.getType() == 1){
data.put("four_"+j,"√");
}
if(anwserVo.getSupplementType() == 1){
data.put("four_supplement",anwserVo.getSupplement());
}
}
break;
case "five":
for (int j = 0; j <anwser.size(); j++) {
AnwserVo anwserVo = anwser.get(j);
if (anwserVo.getType() == 1){
data.put("five_"+j,"√");
}
}
break;
case "six":
for (int j = 0; j <anwser.size(); j++) {
AnwserVo anwserVo = anwser.get(j);
if (anwserVo.getType() == 1){
data.put("six_"+j,"√");
}
if(anwserVo.getSupplementType() == 1){
data.put("six_supplement",anwserVo.getSupplement());
}
}
break;
}
}
// 4. 生成文档
try (XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream()).render(data)) {
String name = "未知";
if (map != null && map.get("name") != null && !"".equals((String)map.get("name"))){
Object nameA = map.get("name");
name = (String) nameA;
}
// 5. 设置响应头
String encodedFileName = URLEncoder.encode(name + "的问卷调查.docx",
StandardCharsets.UTF_8.toString());
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + encodedFileName);
// 6. 输出文件流
template.writeAndClose(response.getOutputStream());
}
}
} catch (IOException e) {
throw new RuntimeException("文件导出失败: " + e.getMessage(), e);
}
}
}
/**
* 查询用户的问卷调查通过id sevice层
* @return
*/
@Override
public Map<String, ArrayList<QuestionVo>> queryUserQuestionnaireById(Integer id) {
try {
Map<String, Object> map1 = questionnaireAdminMapper.queryUserQuestionnaireById(id);
if (map1 == null || map1.get("content") == null) {
return Collections.singletonMap("subject", new ArrayList<>());
}
ObjectMapper objectMapper = new ObjectMapper();
String subject = (String) map1.get("content");
// 使用 TypeReference 指定泛型类型
Map<String, ArrayList<QuestionVo>> map2 = objectMapper.readValue(
subject,
new TypeReference<Map<String, ArrayList<QuestionVo>>>() {}
);
return map2;
} catch (JsonProcessingException e) {
throw new BussinessException("问卷调查转化异常");
}
}
/**
* 查询用户的问卷调查通过id mapper层
* @return
*/
@Select("select content from module_user_questionnaire where id = #{id}")
Map queryUserQuestionnaireById(@Param("id") Integer id);
以下是生成的word模板
9、是否对中医药文化感兴趣?
A. 非常感兴趣 {{one_0}}
B.一般 {{one_1}}
C.不感兴趣 {{one_2}}
10、想通过中医药元宇宙学习到什么知识?
A. 中医药基本理论 {{two_0}}
B.中医药临床知识 {{two_1}}
C.针灸推拿技术 {{two_2}}
D.食疗养生知识 {{two_3}}
E.其他,请填写! {{two_4}} {{two_supplement}}
11、之前是否学习过中医药文化?
A.是 {{three_0}}
B.否 {{three_1}}
12、每天入睡时间是_-点,睡眠时长为_-小时
A.21:00-23:00,7-8小时 {{four_0}}
B.23:00-1:00,6-7小时 {{four_1}}
C.1:00-3:00,5-6小时 {{four_2}}
E.其他,请填写: {{four_3}} {{four_supplement}}
13、认为自己健康吗?
A. 非常健康 {{five_0}}
B.一般 {{five_1}}
C.不健康 {{five_2}}
14、对健康的期许(可多选)
A. 身体健康,不生病 {{six_0}}
B.精神健康,心情愉快 {{six_1}}
C.饮食健康,胃口好、吃饭香 {{six_2}}
D.运动健康,体能充沛 {{six_3}}
E.其他,请填写: {{six_4}} {{six_supplement}}