springboot导出word

记录boot两种导出word的方式
方式一:通过模仿 excel 进行导出
引jar包

		
        
            com.deepoove
            poi-tl
            0.0.3
        

controller

@GetMapping("PoiWord")
    @ApiOperation(value = "导出word",notes = "导出word")
    public void PoiWord(HttpServletResponse response){
        XWPFDocument document= new XWPFDocument();
        List list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("41");
        try {
            // 这里写你在数据库中查出的数据
            for (String str:list){
                //添加标题
                XWPFParagraph titleParagraph = document.createParagraph();
                XWPFRun titleParagraphRun = titleParagraph.createRun();
                titleParagraphRun.setText("汇报人:苌");

                XWPFParagraph titleParagraph1 = document.createParagraph();
                XWPFRun titleParagraphRun1 = titleParagraph1.createRun();
                titleParagraphRun1.setText("提交状态:按时完成");

                XWPFParagraph titleParagraph2 = document.createParagraph();
                XWPFRun titleParagraphRun2 = titleParagraph2.createRun();
                titleParagraphRun2.setText("汇报内容: ");

                //段落
                XWPFParagraph firstParagraph = document.createParagraph();
                XWPFRun run = firstParagraph.createRun();
                run.setText("安静地被罚款敬爱的师父那订房的哈弗连接吧断开连接你疯啦等会呢弗兰克敬爱的很舒服柯兰多爱上的看法较好的快交付拉山东矿机奋达科技暗示分离爱上的看法建安大口径卡掉数据返回阿斯顿开飞机has");
                run.setColor("000000");//设置字体颜色
                run.setFontSize(10);//设置字体大小
                //换行
                XWPFParagraph paragraph3 = document.createParagraph();
                XWPFRun paragraphRun3 = paragraph3.createRun();
                paragraphRun3.setText("\r");//此处换行符无用 代码实际作用为新增一行插入内容为空
            }
            SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
            String fileName = new String("word导出".getBytes("UTF-8"), "iso-8859-1");
            new WordUtil().exportWord(document,response,fileName+sdf.format(new Date()));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("导出成功!!!!");
    }

util

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

public class WordUtil {

    public void exportWord(XWPFDocument document, HttpServletResponse response, String fileName) throws Exception{
        response.setHeader("Content-Disposition","attachment;fileName="+ fileName+".docx");
        response.setContentType("application/msword");
        OutputStream os = response.getOutputStream();
        document.write(os);
        os.flush();
        os.close();
    }
}

方式二:通过模板进行导出
引入jar包

		
        
            cn.afterturn
            easypoi-base
            3.0.3
        
        
            cn.afterturn
            easypoi-web
            3.0.3
        
        
            cn.afterturn
            easypoi-annotation
            3.0.3
        

设定一个模板比如:
springboot导出word_第1张图片
{{#name}} 相当于占位符,代码中会有具体体现
将模板放入:
springboot导出word_第2张图片
controller

@ApiOperation(value = "hahah", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping("/demo/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        Map params = new HashMap<>();
        params.put("username","这是标题");
        params.put("substatus","哈哈");
        params.put("subtime","了咯哦");
        params.put("zhouqi","讷讷");
        params.put("neirong","iiik");
        InputStream is = this.getClass().getResourceAsStream("/word/export.docx");
        ExportWordUtils.exportWord(is,"F:/test","aaa.docx",params,request,response);
    }

这里说下 “F:/test” 为临时文件路径 也可作为存档,代码中会进行删除,注释掉便不会删除

util:

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @data 2020/5/14 0014 -下午 1:58
 */
public class ExportWordUtils {

    /**
     * 导出word
     * 

第一步生成替换后的word文件,只支持docx

*

第二步下载生成的文件

*

第三步删除生成的临时文件

* 模版变量中变量格式:{{foo}} * @param templatePath word模板地址 * @param temDir 生成临时文件存放地址 * @param fileName 文件名 * @param params 替换的参数 * @param request HttpServletRequest * @param response HttpServletResponse */ public static void exportWord(InputStream templatePath, String temDir, String fileName, Map params, HttpServletRequest request, HttpServletResponse response) { Assert.notNull(templatePath,"模板路径不能为空"); Assert.notNull(temDir,"临时文件路径不能为空"); Assert.notNull(fileName,"导出文件名不能为空"); Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式"); if (!temDir.endsWith("/")){ temDir = temDir + File.separator; } File dir = new File(temDir); if (!dir.exists()) { dir.mkdirs(); } try { String userAgent = request.getHeader("user-agent").toLowerCase(); if (userAgent.contains("msie") || userAgent.contains("like gecko")) { fileName = URLEncoder.encode(fileName, "UTF-8"); } else { fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1"); } MyXWPFDocument doc = new MyXWPFDocument(templatePath); WordExportUtil.exportWord07(doc, params); String tmpPath = temDir + fileName; FileOutputStream fos = new FileOutputStream(tmpPath); doc.write(fos); // 设置强制下载不打开 response.setContentType("application/force-download"); // 设置文件名 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); OutputStream out = response.getOutputStream(); doc.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } finally { delFileWord(temDir,fileName);//这一步看具体需求,要不要删 } } /** * 删除零时生成的文件 */ public static void delFileWord(String filePath, String fileName){ File file =new File(filePath+fileName); File file1 =new File(filePath); file.delete(); file1.delete(); } }

参考:
https://blog.csdn.net/weixin_43009990/article/details/89704258
https://blog.csdn.net/qq_37735196/article/details/102802592
https://blog.csdn.net/Tomwildboar/article/details/89856470

你可能感兴趣的:(springboot,java)