java poi生成word文档并下载

我使用的是Springboot框架开发的。首先需要在pom.xml文件中引入以下maven包:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.10-FINAL</version>
</dependency>
 
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.8</version>
</dependency>

然后编写一个word工具类,使用时直接调用即可。

package com.label.tool;
 
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.Map;
 
public class WordTool {
    /**
     * 
     * @param response
     * @throws Exception
     */
    public static void downloadBigActivity(HttpServletResponse response) throws Exception {
        XWPFDocument doc = new XWPFDocument();// 创建Word文件
        XWPFParagraph p = doc.createParagraph();// 新建段落
        p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
        XWPFRun r = p.createRun();//创建标题
        r.setText("2020年元日大型活动情况分析");
        r.setBold(true);//设置为粗体
        r.setColor("000000");//设置颜色
        r.setFontSize(21); //设置字体大小
        r.addCarriageReturn();//回车换行
        XWPFParagraph p1 = doc.createParagraph();
        p1.setAlignment(ParagraphAlignment.BOTH);
 
        XWPFRun c1 = p1.createRun();
        c1.setText("一、12月31日晚上各地将举行各类活动");
        c1.setColor("000000");
        c1.setFontSize(12);
        c1.addCarriageReturn();
        String fileNameURL = URLEncoder.encode("myWord.doc", "UTF-8");
        response.setCharacterEncoding("UTF-8");
        //response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameURL + ";" + "filename*=utf-8''" + fileNameURL);
        //response.setContentType("application/octet-stream");
        //刷新缓冲
        response.flushBuffer();
        OutputStream ouputStream = response.getOutputStream();
        //workbook将Excel写入到response的输出流中,供页面下载该Excel文件
        doc.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }
   
}
posted @ 2021-04-08 14:20  岁月淡忘了谁  阅读(1490)  评论(0编辑  收藏  举报