spring boot实现自动输出word文档功能的实例代码

 更新时间:2021年04月20日 14:44:01   作者:离人散  
这篇文章主要介绍了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();
        }
    }

效果:

在这里插入图片描述

到此这篇关于spring boot实现自动输出word文档功能的文章就介绍到这了,更多相关spring boot自动输出word文档内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java堆栈类使用实例(java中stack的使用方法)

    java堆栈类使用实例(java中stack的使用方法)

    java中stack的使用方法,堆栈是一种"后进先出"(LIFO) 的数据结构, 只能在一端进行插入(称为"压栈") 或删除 (称为"出栈")数据的操作,下面看示例吧
    2013-12-12
  • idea2020安裝MybatisCodeHelper插件的图文教程

    idea2020安裝MybatisCodeHelper插件的图文教程

    这篇文章主要介绍了idea2020安裝MybatisCodeHelper插件的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Simple Java Mail邮件发送实现过程解析

    Simple Java Mail邮件发送实现过程解析

    这篇文章主要介绍了Simple Java Mail邮件发送实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • java查找字符串中的包含子字符串的个数实现代码

    java查找字符串中的包含子字符串的个数实现代码

    下面小编就为大家带来一篇java查找字符串中的包含子字符串的个数实现代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • 详解5种Java中常见限流算法

    详解5种Java中常见限流算法

    在高并发系统中,出于系统保护角度考虑,通常会对流量进行限流;不但在工作中要频繁使用,而且也是面试中的高频考点。本文就为大家整理了5种Java中常见限流算法,需要的可以参考一下
    2023-04-04
  • 老生常谈比较排序之堆排序

    老生常谈比较排序之堆排序

    下面小编就为大家带来一篇老生常谈比较排序之堆排序。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • java中数组的定义及使用方法(推荐)

    java中数组的定义及使用方法(推荐)

    下面小编就为大家带来一篇java中数组的定义及使用方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-07-07
  • 彻底搞懂Java多线程(三)

    彻底搞懂Java多线程(三)

    这篇文章主要给大家介绍了关于Java面试题之多线程和高并发的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2021-07-07
  • 详谈ServiceLoader实现原理

    详谈ServiceLoader实现原理

    下面小编就为大家带来一篇详谈ServiceLoader实现原理。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02
  • 详解使用SSM实现简单工作流系统之实现篇

    详解使用SSM实现简单工作流系统之实现篇

    这篇文章主要介绍了使用SSM实现简单工作流系统之实现篇,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12

最新评论