溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

spring boot怎么實(shí)現(xiàn)自動(dòng)輸出word文檔功能

發(fā)布時(shí)間:2021-04-30 10:58:02 來(lái)源:億速云 閱讀:564 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了spring boot怎么實(shí)現(xiàn)自動(dòng)輸出word文檔功能,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程,SpringBoot也是一個(gè)服務(wù)于框架的框架,服務(wù)范圍是簡(jiǎn)化配置文件。

spring boot實(shí)現(xiàn)自動(dòng)輸出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>

首先創(chuàng)建相關(guān)的實(shí)體類、編寫需要用到的sql查詢。

import lombok.Data;

// 選擇題實(shí)體
@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;

//填空題實(shí)體類
@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;

//判斷題實(shí)體類
@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; //題目解析
}

創(chuàng)建好要用到的實(shí)體類之后,利用mybatis寫sql查詢,可以分為兩種:1、配置mapper.xml文件路徑,在xml文件中編寫sql語(yǔ)句。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底層查詢后,需要?jiǎng)?chuàng)建service及其實(shí)現(xiàn)類來(lái)調(diào)用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{
    //由于題目應(yīng)于考試信息對(duì)應(yīng) 所以需要先查出考試信息后根據(jù)pageId來(lái)查找對(duì)應(yīng)的組卷信息
        ExamManage res = examManageService.findById(examCode);
        int paperId = res.getPaperId();
        List<MultiQuestion> multiQuestionRes = multiQuestionService.findByIdAndType(paperId);   //選擇題題庫(kù) 1
        List<FillQuestion> fillQuestionsRes = fillQuestionService.findByIdAndType(paperId);     //填空題題庫(kù) 2
        List<JudgeQuestion> judgeQuestionRes = judgeQuestionService.findByIdAndType(paperId);
        //響應(yīng)到客戶端
        XWPFDocument document= new XWPFDocument();
        //分頁(yè)
        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 {
            //設(shè)置相應(yīng)頭
            this.setResponseHeader(response, res.getSource() + "試卷.doc");
            //輸出流
            OutputStream os = response.getOutputStream();
            document.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 發(fā)送響應(yīng)流方法
     */
    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);
            //遵守緩存規(guī)定
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

效果:

spring boot怎么實(shí)現(xiàn)自動(dòng)輸出word文檔功能

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“spring boot怎么實(shí)現(xiàn)自動(dòng)輸出word文檔功能”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI