java按照模板导出word 文档

需求导出表格数据到word 文档中

  1. 新建word 文档
    在这里插入图片描述
    通过${ValueList1.value1} 来往里面添加数据, ValueList 即每一行数据的集合
    保存word 文档,另存为 xml 格式
    2、打开xml文件
    搜索 <w:tr> 标识符,在相应的 行 前后 加上 <#list TestEntityList as TestEntity> </#list>
    如图所示
    在这里插入图片描述
    3.保存文件 ,将文件后缀 改为ftl 格式 ,即模板创建完毕

下载导出工具类:
所用的jar包

org.freemarker
freemarker
2.3.30

package cn.stephen.study.demoproject.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.stephen.study.demoproject.entity.Value;
import cn.stephen.study.demoproject.service.SBJCYJService;
import cn.stephen.study.demoproject.service.impl.SBJCYJServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import freemarker.template.Version;

import java.util.*;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;


import cn.stephen.study.demoproject.entity.TestEntity;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

@Component
public class WordUtil{
    private Configuration configuration = null;

    public WordUtil() {
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("UTF-8");
    }


    /**
     *   将文本信息转为word输出
     * @param
     * @throws Exception
     */
public File createDoc() throws IOException {
    Map<String,Object> dataMap = new HashMap<>();
    getData(dataMap); //创建数据
    Configuration configuration = new Configuration(new Version("2.3.0"));
    configuration.setDefaultEncoding("UTF-8");
//        configuration.setClassForTemplateLoading(this.getClass(), "D:/"); //模板文件所在路径
    configuration.setDirectoryForTemplateLoading(new File("D:\\tool"));
    Template t = null;
    String fileName = "D:\\test.doc";
    File file = new File(fileName);
    try {
        t = configuration.getTemplate("aaa.ftl"); //获取模板文件
        t.setEncoding("utf-8");

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),"utf-8"));
        t.process(dataMap, out);  //将填充数据填入模板文件并输出到目标文件
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TemplateException e) {
        e.printStackTrace();
    }

    return file;
}

/**
 * 导出word 并提供下载
 * @param response
 */
public void download(HttpServletResponse response) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        File file = createDoc();
        response.setContentType("application/msword;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment; filename=\""
                + new String(file.getName().getBytes(),"iso-8859-1") + "\"");

        bis = new BufferedInputStream(new FileInputStream(file));
        bos = new BufferedOutputStream(response.getOutputStream());

        byte[] buff = new byte[10240];
        int bytesRead;
        while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }

        bis.close();
        bos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//获得图片的base64编码
private String getBase64(String imgUrl) {
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    URL url = null;
    InputStream in = null;
    HttpURLConnection httpUrl = null;
    byte[] by = new byte[1024];

    try {
        url = new URL(imgUrl);
        httpUrl = (HttpURLConnection)url.openConnection();
        httpUrl.connect();
        in = httpUrl.getInputStream();
        int len = -1;
        while((len = in.read(by)) != -1) {
            data.write(by, 0, len);
        }

        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data.toByteArray());
}

private void getData(Map<String, Object> dataMap) {
    List<Value> ValueList =new ArrayList<>();
    for (List<String> values : list1) {
        Value value1=new Value();
        if(values.size()>0){
           for(int i=0 ;i<10;i++){
            value1.setValue1(i);
            value1.setValue2(i);
            value1.setValue3(i);
            value1.setValue4(i);
            value1.setValue5(i);
            value1.setValue6(i);
            value1.setValue7(i);
            value1.setValue8(i);
            value1.setValue9(i);
            ValueList.add(value1);
            }
        }
    }
    dataMap.put("ValueList", ValueList);
}


}

遇到的问题:
开始通过第一种方式在读取 模板文件位置时一直找不到,后面改为第二种方式
1.configuration.setClassForTemplateLoading(this.getClass(), “D:/”); //模板文件所在路径
2. configuration.setDirectoryForTemplateLoading(new File(“D:\tool”));

jar包版本也要注意,

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值