栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java导出word 采用FreeMarker生成word文档

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java导出word 采用FreeMarker生成word文档

FreeMarker生成word文档

这边采用的是FreeMarker生成word文档的方式。
还有一种比较推荐的是easypoi框架。

本文说明FreeMarker。这边就不做easypoi案例讲解,直接参照官网

easypoi文档地址:https://opensource.afterturn.cn/doc/easypoi.html#601
gitee地址:https://gitee.com/tianj/easypoi

文章目录
  • FreeMarker生成word文档
  • 简介
  • 一、word模板设计
    • 1.1、流程
    • 1.2、如图
  • 二、demo总览
  • 三、代码实现
    • 1.1、导入依赖
    • 1.2、导入 .ftl 模板文件
    • 1.3、代码实现
  • 四、word里面的遍历说明
  • 五、浏览器访问地址+效果
  • 六、完整的模板内容


简介

FreeMarker生成word文档的功能是由XML+FreeMarker来实现的。
先把word文件另存为xml,在xml文件中插入特殊的字符串占位符,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板,编码调用FreeMarker实现文本替换并输出Doc


一、word模板设计 1.1、流程
  1. 新建word文件,写好内容排版
  2. 另存为xml格式
  3. 修改后缀为.ftl
1.2、如图
  1. 新建文件

  2. 添加内容+排版+占位符

  3. 另存为xml

  4. 查看是否乱码

  5. 修改后缀为.ftl文件,查看是否乱码,完成

二、demo总览

springboot 工程

三、代码实现 1.1、导入依赖
  
 
      org.apache.commons
      commons-lang3
      3.7
  

  
  
      org.freemarker
      freemarker
      2.3.23
  
1.2、导入 .ftl 模板文件

1.3、代码实现

controller层 WordController.java

package sqy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sqy.domian.Card;
import sqy.utils.DownloadUtil;
import sqy.utils.WordUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;



@Controller
public class WordController {

    @ResponseBody//返回的是字符串 不是跳页面
    @GetMapping("/wordDownload")
    public String wordDownload() throws Exception {
        Map dataMap = new HashMap();
        dataMap.put("userName","张三");//姓名
        dataMap.put("userNo", "888888888888888888");//编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Calendar now = Calendar.getInstance();
        String dateStr = sdf.format(now.getTime());
        dataMap.put("downTime", dateStr);// 当前时间

        //表格
        ArrayList cardList = new ArrayList<>();
        for (int i = 0; i <5 ; i++) {
            Card card = new Card();
            card.setCardName(i+"号项目");
            card.setPrice(i+"00元");
            cardList.add(card);
        }
        dataMap.put("cardList", cardList);//表格

        //加载资源文件
        ByteArrayOutputStream outputStream = WordUtil.process(dataMap, "/templates/" + "userWord.ftl");
         //直接从浏览器冲刷下来
        DownloadUtil.downLoad(outputStream, getResponse(), "document.docx");
        return null;
    }


    private HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
}


下载工具类 DownloadUtil.java

package sqy.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class DownloadUtil {
    
    public static void downLoad(String filePath, String fileName) throws Exception {
        InputStream in = null;
        OutputStream os = null;
        if (StringUtils.isBlank(filePath)) {
            throw new Exception("文件路径不能为空!");
        }
        if (StringUtils.isBlank(fileName)) {
            throw new Exception("文件名称不能为空!");
        }
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath + fileName);
            // 打开本地文件流
            in = classPathResource.getInputStream();
            // 激活下载操作
            os = response.getOutputStream();
            // 循环写入输出流
            byte[] b = new byte[1024];
            int length;
            while ((length = in.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("下载失败!");
        } finally {
            if (in != null) {
                in.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

    
    public static void downLoad(String fileName) throws Exception {
        InputStream in = null;
        OutputStream os = null;
        if (StringUtils.isBlank(fileName)) {
            throw new Exception("文件名称不能为空!");
        }
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        try {
            ClassPathResource classPathResource = new ClassPathResource("document/" + fileName);
            // 打开本地文件流
            in = classPathResource.getInputStream();
            // 激活下载操作
            os = response.getOutputStream();
            // 循环写入输出流
            byte[] b = new byte[1024];
            int length;
            while ((length = in.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("下载失败!");
        } finally {
            if (in != null) {
                in.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

    
    public static void downLoad(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws Exception{
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment; filename=" + returnName);
        response.setContentLength(byteArrayOutputStream.size());
        OutputStream outputstream = response.getOutputStream();			//取得输出流
        byteArrayOutputStream.writeTo(outputstream);					//写到输出流
        byteArrayOutputStream.close();									//关闭
        outputstream.flush();											//刷数据
    }

    
    public static void downloadByUrl(String fileName , String path,  HttpServletResponse response)  {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        try {
            // 获取外部文件流
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            
            int len = 0;
            // 输出 下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Cache-Control", "no-cache");
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                }
            }
        }
    }
}


word工具类 WordUtil.java

package sqy.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;


public final class WordUtil {
    private static Configuration configuration = null;

    private WordUtil() {
        throw new AssertionError();
    }

    
    public static synchronized ByteArrayOutputStream process(Map root, String template) {

        if (null == root ) {
            throw new RuntimeException("数据不能为空");
        }

        if (null == template) {
            throw new RuntimeException("模板文件不能为空");
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String templatePath = template.substring(0, template.lastIndexOf("/"));
        String templateName = template.substring(template.lastIndexOf("/") + 1, template.length());

        if (null == configuration) {
            configuration = new Configuration(Configuration.VERSION_2_3_23);  // 这里Configurantion对象不能有两个,否则多线程访问会报错
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassicCompatible(true);
        }
        configuration.setClassForTemplateLoading(WordUtil.class, templatePath);

        Template t = null;
        try {
            t = configuration.getTemplate(templateName);
            Writer w = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            t.process(root, w);  // 这里w是一个输出地址,可以输出到任何位置,如控制台,网页等
            w.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return outputStream;
    }

}

实体类 Card.java

package sqy.domian;

import org.springframework.stereotype.Component;


@Component
public class Card {
    private String cardName;
    private String price;

    public String getCardName() {
        return cardName;
    }

    public void setCardName(String cardName) {
        this.cardName = cardName;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

四、word里面的遍历说明

使用标签 <#list cardList as card>
将需要遍历的字段给包裹起来
如图:

普通取值说明:在准备模板是时候就写好了占位符了

五、浏览器访问地址+效果

访问下载

下载的效果

六、完整的模板内容



    
        
            
                
                
                
                
            
        
    
    
        
            
                
                
                
                
                
            
        
    
    
        
            
                
                    
                        
                            
                            
                                
                                
                                
                                
                            
                        
                        
                            
                                
                                
                                
                                
                            
                            姓名:${userName}。编码:${userNo}
                        
                    
                    
                        
                            
                            
                            
                                
                                
                                
                                
                            
                        
                    
                    
                        
                            
                            
                            
                                
                                
                                
                                
                            
                        
                        
                            
                                
                                
                                
                                
                            
                            费用单
                        
                    


                    
                        
                            
                            
                            
                            
                                
                                
                                
                                
                                
                                
                            
                            
                            
                                
                                
                            
                        
                        
                            
                            
                        
                        

                            
                                
                                    
                                    
                                    
                                    
                                    
                                    
                                
                                
                                    
                                    
                                
                            

                            
                                
                                    
                                
                                
                                    
                                        
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                        项目
                                    
                                
                            
                            
                                
                                    
                                
                                
                                    
                                        
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                        费用
                                    
                                
                            
                        
                        <#list cardList as card>
                        
                            
                                
                                    
                                    
                                    
                                    
                                    
                                    
                                
                                
                                    
                                    
                                
                            
                            
                                
                                    
                                
                                
                                    
                                        
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                        ${card.cardName}
                                    
                                
                            

                            
                                
                                    
                                
                                
                                    
                                        
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                            
                                            
                                        
                                        ${card.price}
                                    
                                
                            
                        
                        
                    

                    
                        
                            
                            
                            
                                
                                
                                
                                
                            
                        
                        
                        
                    
                    
                    
                        
                            
                            
                            
                                
                                
                                
                                
                            
                        
                        
                            
                                
                                
                                
                                
                            
                            下载时间:${downTime}
                        
                    
                    
                    
                        
                        
                        
                        
                    
                
            
        
    
    
        
            
                
            
        
    
    
        
            
                
                    
                
            
        
    
    
        
            
                
                    
                
            
        
    
    
        
            
                
                1
                0
                0
                0
                0
                0
                false
                false
                0
                WPS Office_11.8.6.8810_F1E327BC-269C-435d-A152-05C5408002CA
                0
            
        
    
    
        
            
                2021-12-21T02:42:00Z
                11202
                11202
                2021-12-21T03:04:01Z
            
        
    
    
        
            
                
                    2052-11.8.6.8810
                
            
        
    
    
        
            
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                
            
        
    
    
        
            
                
                
                
                
                
                
                
                
                
                
                
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                
                
                
                
            
        
    
    
        
            
                
                    
                        
                            
                        
                    
                
                
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                
                
                    
                    
                    
                    
                        
                        
                    
                    
                        
                        
                        
                        
                        
                    
                
                
                    
                    
                    
                
                
                    
                    
                    
                    
                    
                        
                            
                            
                            
                            
                        
                    
                
                
                    
                    
                    
                    
                        
                        
                    
                    
                        
                            
                            
                            
                            
                            
                            
                        
                    
                
            
        
    
    
        
            
                
                    
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                        
                            
                        
                    
                    
                        
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                        
                        
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                        
                    
                    
                        
                            
                                
                            
                            
                                
                                    
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                    
                                
                                
                            
                            
                                
                                    
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                    
                                
                                
                            
                        
                        
                            
                                
                                    
                                
                                
                                
                            
                            
                                
                                    
                                
                                
                                
                            
                            
                                
                                    
                                
                                
                                
                            
                        
                        
                            
                                
                            
                            
                                
                            
                            
                                
                                    
                                        
                                            
                                        
                                    
                                
                            
                        
                        
                            
                                
                            
                            
                                
                                    
                                    
                                
                            
                            
                                
                                    
                                        
                                            
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                        
                                    
                                
                                
                            
                        
                    
                
                
            
        
    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号