java使用freemarker动态生成word

1、首先建立test.docx,内容如下。(生成的word文档如下形式):姓名,电话,图片

2、将word另存为xml

3、用编辑器编辑test.xml,找到图片所在的位置

替换后为:

4、保存,将test.xml改成test.ftl

5、java建立实体,对应三个字段

pom.xml

<dependency>
             <groupId>org.freemarker</groupId>
             <artifactId>freemarker</artifactId>
</dependency>

public class Data {
    
    private String name;
    
    private String tel;
    
    private String imgbase64;

}

6、建立DocumentHandler ,来处理数据

import java.io.BufferedWriter; 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStreamWriter;
import java.io.Writer;  
import java.util.HashMap; 
import java.util.Map;

import org.apache.tomcat.util.codec.binary.Base64;

import freemarker.template.Configuration; 
import freemarker.template.Template; 
import freemarker.template.TemplateException; 
/**
 * 文件处理
 */
public class DocumentHandler { 
    private Configuration configuration = null; 
    public DocumentHandler() { 
        configuration = new Configuration(); 
        configuration.setDefaultEncoding("utf-8"); 
    } 
    public void createDoc() throws Exception { 
        Data data=new Data(); 
        getData(data); 

       这里根据自己的实际情况来,本例是“/”
        configuration.setClassForTemplateLoading(this.getClass(),"/"); 
        Template t=null; 
        try { 
            //test.ftl为要装载的模板 
            t = configuration.getTemplate("test.ftl"); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        //输出文档路径及名称 
        File outFile = new File("E:\\test_new.doc"); 
        Writer out = null; 
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try { 
            t.process(data, out); 
        } catch (TemplateException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
     private void getData(Data data) throws Exception{ 
          data.setName("lw");
          data.setTel("111111111");

          将图片E:\\test.png,打印到word
          File file = new File("E:\\test.png");
          FileInputStream fis = new FileInputStream(file);
          byte[] imgData = new byte[fis.available()];
          fis.read(imgData);
          fis.close();
          String imgbase64 = new Base64().encodeAsString(imgData); 
          data.setImgbase64(imgbase64);
          
      } 
     
     public static void main(String[] args) throws Exception {
         DocumentHandler dh=new DocumentHandler();
         dh.createDoc();
    }

7、执行一下,即可生成word。

猜你喜欢

转载自blog.csdn.net/xiaohanshasha/article/details/85100316