spring boot实现自动输出word文档功能的实例代码
作者:离人散 发布时间:2021-11-10 13:37:51
标签:spring,boot,自动输出,word文档
spring boot实现自动输出word文档功能
本文用到Apache POI组件
组件依赖在pom.xml文件中添加
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
首先创建相关的实体类、编写需要用到的sql查询。
import lombok.Data;
// 选择题实体
@Data
public class MultiQuestion {
private Integer questionId;
private String subject;
private String section;
private String answerA;
private String answerB;
private String answerC;
private String answerD;
private String question;
private String level;
private String rightAnswer;
private String analysis; //题目解析
private Integer score;
}
import lombok.Data;
//填空题实体类
@Data
public class FillQuestion {
private Integer questionId;
private String subject;
private String question;
private String answer;
private Integer score;
private String level;
private String section;
private String analysis; //题目解析
}
import lombok.Data;
//判断题实体类
@Data
public class JudgeQuestion {
private Integer questionId;
private String subject;
private String question;
private String answer;
private String level;
private String section;
private Integer score;
private String analysis; //题目解析
}
创建好要用到的实体类之后,利用mybatis写sql查询,可以分为两种:1、配置mapper.xml文件路径,在xml文件中编写sql语句。2、直接使用注解。本文使用方法为第二种。
@Mapper
public interface MultiQuestionMapper {
/**
* select * from multiquestions where questionId in (
* select questionId from papermanage where questionType = 1 and paperId = 1001
* )
*/
@Select("select * from multi_question where questionId in (select questionId from paper_manage where questionType = 1 and paperId = #{paperId})")
List<MultiQuestion> findByIdAndType(Integer PaperId);
@Select("select * from multi_question")
IPage<MultiQuestion> findAll(Page page);
/**
* 查询最后一条记录的questionId
* @return MultiQuestion
*/
@Select("select questionId from multi_question order by questionId desc limit 1")
MultiQuestion findOnlyQuestionId();
@Options(useGeneratedKeys = true,keyProperty = "questionId")
@Insert("insert into multi_question(subject,question,answerA,answerB,answerC,answerD,rightAnswer,analysis,section,level) " +
"values(#{subject},#{question},#{answerA},#{answerB},#{answerC},#{answerD},#{rightAnswer},#{analysis},#{section},#{level})")
int add(MultiQuestion multiQuestion);
@Select("select questionId from multi_question where subject =#{subject} order by rand() desc limit #{pageNo}")
List<Integer> findBySubject(String subject,Integer pageNo);
}
//填空题
@Mapper
public interface FillQuestionMapper {
@Select("select * from fill_question where questionId in (select questionId from paper_manage where questionType = 2 and paperId = #{paperId})")
List<FillQuestion> findByIdAndType(Integer paperId);
@Select("select * from fill_question")
IPage<FillQuestion> findAll(Page page);
/**
* 查询最后一条questionId
* @return FillQuestion
*/
@Select("select questionId from fill_question order by questionId desc limit 1")
FillQuestion findOnlyQuestionId();
@Options(useGeneratedKeys = true,keyProperty ="questionId" )
@Insert("insert into fill_question(subject,question,answer,analysis,level,section) values " +
"(#{subject,},#{question},#{answer},#{analysis},#{level},#{section})")
int add(FillQuestion fillQuestion);
@Select("select questionId from fill_question where subject = #{subject} order by rand() desc limit #{pageNo}")
List<Integer> findBySubject(String subject,Integer pageNo);
}
//判断题
@Mapper
public interface JudgeQuestionMapper {
@Select("select * from judge_question where questionId in (select questionId from paper_manage where questionType = 3 and paperId = #{paperId})")
List<JudgeQuestion> findByIdAndType(Integer paperId);
@Select("select * from judge_question")
IPage<JudgeQuestion> findAll(Page page);
/**
* 查询最后一条记录的questionId
* @return JudgeQuestion
*/
@Select("select questionId from judge_question order by questionId desc limit 1")
JudgeQuestion findOnlyQuestionId();
@Insert("insert into judge_question(subject,question,answer,analysis,level,section) values " +
"(#{subject},#{question},#{answer},#{analysis},#{level},#{section})")
int add(JudgeQuestion judgeQuestion);
@Select("select questionId from judge_question where subject=#{subject} order by rand() desc limit #{pageNo}")
List<Integer> findBySubject(String subject,Integer pageNo);
}
写好mapper底层查询后,需要创建service及其实现类来调用mapper底层。例如:
public interface JudgeQuestionService {
List<JudgeQuestion> findByIdAndType(Integer paperId);
IPage<JudgeQuestion> findAll(Page<JudgeQuestion> page);
JudgeQuestion findOnlyQuestionId();
int add(JudgeQuestion judgeQuestion);
List<Integer> findBySubject(String subject,Integer pageNo);
}
@Service
public class JudgeQuestionServiceImpl implements JudgeQuestionService {
@Autowired
private JudgeQuestionMapper judgeQuestionMapper;
@Override
public List<JudgeQuestion> findByIdAndType(Integer paperId) {
return judgeQuestionMapper.findByIdAndType(paperId);
}
@Override
public IPage<JudgeQuestion> findAll(Page<JudgeQuestion> page) {
return judgeQuestionMapper.findAll(page);
}
@Override
public JudgeQuestion findOnlyQuestionId() {
return judgeQuestionMapper.findOnlyQuestionId();
}
@Override
public int add(JudgeQuestion judgeQuestion) {
return judgeQuestionMapper.add(judgeQuestion);
}
@Override
public List<Integer> findBySubject(String subject, Integer pageNo) {
return judgeQuestionMapper.findBySubject(subject,pageNo);
}
}
最后将输出文件方法写在controller层:
@RequestMapping("/exam/exportWord")
public void exportWord(int examCode, HttpServletResponse response) throws FileNotFoundException{
//由于题目应于考试信息对应 所以需要先查出考试信息后根据pageId来查找对应的组卷信息
ExamManage res = examManageService.findById(examCode);
int paperId = res.getPaperId();
List<MultiQuestion> multiQuestionRes = multiQuestionService.findByIdAndType(paperId); //选择题题库 1
List<FillQuestion> fillQuestionsRes = fillQuestionService.findByIdAndType(paperId); //填空题题库 2
List<JudgeQuestion> judgeQuestionRes = judgeQuestionService.findByIdAndType(paperId);
//响应到客户端
XWPFDocument document= new XWPFDocument();
//分页
XWPFParagraph firstParagraph = document.createParagraph();
//格式化段落
firstParagraph.getStyleID();
XWPFRun run = firstParagraph.createRun();
int i = 1;
run.setText("一、选择题" + "\r\n"); //换行
for (MultiQuestion multiQuestion : multiQuestionRes) {
String str = multiQuestion.getQuestion();
String str1 = multiQuestion.getAnswerA();
String str2 = multiQuestion.getAnswerB();
String str3 = multiQuestion.getAnswerC();
String str4 = multiQuestion.getAnswerD();
run.setText(i + ". " + str + "\r\n");
run.setText("A. " + str1 + "\r\n");
run.setText("B. " + str2 + "\r\n");
run.setText("C. " + str3 + "\r\n");
run.setText("D. " + str4 + "\r\n");
i++;
}
run.setText("二、填空题" + "\r\n");
for (FillQuestion fillQuestion : fillQuestionsRes) {
String str = fillQuestion.getQuestion();
run.setText(i + ". " + str + "\r\n");
i++;
}
run.setText("三、判断题" + "\r\n");
for (JudgeQuestion judgeQuestion : judgeQuestionRes) {
String str = judgeQuestion.getQuestion();
run.setText(i + ". " + str + "\r\n");
i++;
}
document.createTOC();
try {
//设置相应头
this.setResponseHeader(response, res.getSource() + "试卷.doc");
//输出流
OutputStream os = response.getOutputStream();
document.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送响应流方法
*/
private void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
//遵守缓存规定
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
效果:
来源:https://blog.csdn.net/qq_42793254/article/details/115859007
0
投稿
猜你喜欢
- 前言这几天同事跟我在升级Android target SDK和build tool版本的时候,碰到了一个非常搞笑的问题,基本可以算作是“坑”
- 创建类第一步新建一个java类QSV,构造函数传入需要解析的文件名称。public class QSV {private RandomAcc
- 本文为大家分享了java画出五子棋游戏棋盘的方法,供大家参考,具体内容如下棋盘模块:画五子棋棋盘:19条横线、19条竖线步骤一:显示棋盘我有
- 一、背景在上一篇文章中,我们使用Seata整合了SpringBoot,在这篇文章中我们使用Seata整合SpringCloud。同时有了上一
- 之前我一直认为 Mybatis 框架下已经实现预编译机制,很多东西都封装好了,应该基本上不会再有 SQL 注入问题了。近期在渗透中发现,在实
- java try catch异常后还会继续执行吗catch中如果你没有再抛出异常,那么catch之后的代码是可以继续执行的,但是try中,报
- 本文研究的主要是Java中finally和return的关系,具体介绍和实例如下所示。finally 和 return 关系的总结1.try
- Java中对象与C++中对象的放置安排的对比概要:Java中,所有的对象都存放在堆(Heap,一种通用的内存池)中;而对象的引用是存放在堆栈
- 由于byte是一个8位字节所以可以用它来存放数组为8的boolean数组,这些在通信协议会经常用到。这里给出一个java代码对其互相转换的。
- 默认情况下Spring Boot使用了内嵌的Tomcat服务器,项目最终被打成jar包运行,每个jar包可以被看作一个独立的Web服务器。传
- 一、背景介绍在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLCo
- 本文实例为大家分享了java实现双色球抽奖的具体代码,供大家参考,具体内容如下实现双色球先考虑整体思路:1.随机生成7位数的数组为大奖号码(
- 一、概述在微服务架构中,我们将系统拆分成了很多服务单元,各单元的应用间通过服务注册与订阅的方式互相依赖。由于每个单元都在不同的进程中运行,依
- 使用 transient 修饰private transient String noColumn;使用 static 修饰private s
- Mybatis-Spring当我们使用mybatis和spring整合后为什么下面的代码可以运行?一个问题:我就写了个mapper接口为什么
- SpringBoot集成Redis 1.添加redis依赖<dependency> <groupId
- FrameLayout 在这个布局中,所有的子元素都不能被指定放置的位置,他们统统防御这块区域的左上角, 并且后面的子元素直接覆盖在前面的子
- JavaWeb项目部署到服务器详细步骤本地准备在eclipse中将项目打成war文件:鼠标右键要部署到服务器上的项目导出项目数据库文件MyS
- 弃用内容先来纠正一个误区。主要之前在版本更新介绍的时候,存在一些表述上的问题。导致部分读者认为这次的更新是Datasource本身初始化的调
- 前提:windows上安装jdk1.启动jar脚本@echo offSTART "app" javaw -jar app