用 Freemarker 生成 word 文档

1.       word写一个需要导出的word模板,然后存为xml格式。

2.       xml中需要动态修改内容的地方,换成freemarker的标识符,例如:

 1     <w:p wsp:rsidR="00D02906" wsp:rsidRDefault="00FA4C58" wsp:rsidP="00FA4C58">
 2         <w:pPr>
 3             <w:jc w:val="center"/>
 4             <w:rPr>
 5                 <w:rFonts w:hint="fareast"/>
 6             </w:rPr>
 7         </w:pPr>
 8         <w:r>
 9             <w:t>${year}</w:t>
10         </w:r>
11         <w:r>
12             <w:rPr>
13                 <wx:font wx:val="宋体"/>
14             </w:rPr>
15             <w:t>年度工作报告</w:t>
16         </w:r>

17     </w:p> 

3.       用代码生成:
 1 import freemarker.template.Configuration;
 2 import freemarker.template.Template;
 3 
 4 import java.io.*;
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 
 8 /**
 9  * @Class name:    CreateDoc
10  * <p/>
11  * Short description on the purpose of the program.
12  * @author : youfeng
13  * @modified : 8/29/11
14  */
15 public class CreateDoc {
16 
17     private Configuration configuration = null;
18 
19     public CreateDoc() {
20         configuration = new Configuration();
21         configuration.setDefaultEncoding("utf-8");
22     }
23 
24     public void create() throws Exception {
25         Map<String, Object> map = new HashMap<String, Object>();
26         map.put("date""2011");
27         map.put("modifyDate""2011/8/29");
28         map.put("modifyUser""Zhu You Feng");
29 
30         configuration.setClassForTemplateLoading(this.getClass(), "/docTemplate/");
31         Template t = configuration.getTemplate("doc1.ftl");
32         File outFile = new File("D:/outFile.doc");
33         Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
34         t.process(map, out);
35     }
36 
37     public static void main(String[] args) throws Exception {
38         new CreateDoc().create();
39 
40     }
41 }

 

添加图片

如果你需要在word中添加图片,那你就在第一步制作模板时,加入一张图片占位,然后打开xml文档,可以看到如下的一片base64编码后的代码:

1 <w:binData w:name="wordml://03000001.png" xml:space="preserve">iVBORw0…(很省略很省略)…CC</w:binData>

只要将base64的代码替换成例如:${image},如下:

1 <w:binData w:name="wordml://03000001.png" xml:space="preserve">${image}</w:binData>

这里要注意>${image}<这尖括号中间不能加任何其他的诸如空格,tab,换行等符号。

然后用代码生成:

 1 import freemarker.template.Configuration;
 2 import freemarker.template.Template;
 3 import sun.misc.BASE64Encoder;
 4 
 5 import java.io.*;
 6 import java.util.HashMap;
 7 import java.util.Map;
 8 
 9 /**
10  * @Class name:    CreateDoc
11  * @author: youfeng
12  * @modified: 8/29/11
13  */
14 public class CreateDocWithImage {
15 
16     private Configuration configuration = null;
17 
18     public CreateDocWithImage() {
19         configuration = new Configuration();
20         configuration.setDefaultEncoding("utf-8");
21     }
22 
23     public void create() throws Exception {
24         Map<String, Object> map = new HashMap<String, Object>();
25         map.put("year""2011");
26         map.put("person""Zhu You Feng");
27         map.put("image", getImageStr());
28 
29         configuration.setClassForTemplateLoading(this.getClass(), "/docTemplate/");
30         Template t = configuration.getTemplate("doc2.ftl");
31         File outFile = new File("D:/outFile.doc");
32         Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
33         t.process(map, out);
34     }
35 
36     private String getImageStr() {
37         String imgFile = "d:/test.jpg";
38         InputStream in = null;
39         byte[] data = null;
40         try {
41             in = new FileInputStream(imgFile);
42             data = new byte[in.available()];
43             in.read(data);
44             in.close();
45         } catch (IOException e) {
46             e.printStackTrace();
47         }
48         BASE64Encoder encoder = new BASE64Encoder();
49         return encoder.encode(data);
50     }
51 
52     public static void main(String[] args) throws Exception {
53         new CreateDocWithImage().create();
54 
55     }
56 }

 

自定义载入模板

 

   1 import freemarker.cache.TemplateLoader;

  2 import freemarker.template.Configuration;
  3 import freemarker.template.Template;
  4 import freemarker.template.TemplateException;
  5 import sun.misc.BASE64Encoder;
  6 
  7 import java.io.*;
  8 import java.util.HashMap;
  9 import java.util.Map;
 10 
 11 public class DocumentGenerator {
 12     private Configuration configuration = null;
 13 
 14     public static void main(String[] args) throws Exception {
 15         Map<String, Object> map = new HashMap<String, Object>();
 16         map.put("date""2012");
 17         map.put("modifyDate""2011/8/29");
 18         map.put("modifyUser""Zhu You Feng");
 19         new DocumentGenerator().createDoc("""D:/outFile2.doc", map);
 20     }
 21 
 22     public DocumentGenerator() {
 23         configuration = new Configuration();
 24         configuration.setDefaultEncoding("utf-8");
 25         configuration.setClassicCompatible(true);
 26         configuration.setTemplateLoader(new ByteArrayStreamTemplateLoader(new ByteArrayInputStream(
 27                         getBytesFromFile(new File("D:/ownProject/freemarkerToDoc/src/main/resources/docTemplate/doc1.ftl"))
 28                 )));
 29     }
 30 
 31     /**
 32      * @param fileName
 33      * @param outFileName
 34      * @param dataMap
 35      */
 36     public void createDoc(String fileName, String outFileName, Map dataMap) {
 37         Template t = null;
 38         try {
 39             t = configuration.getTemplate(fileName);
 40         } catch (IOException e) {
 41             e.printStackTrace();
 42         }
 43         File outFile = new File(outFileName);
 44         Writer out = null;
 45         try {
 46             out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
 47         } catch (FileNotFoundException e1) {
 48             e1.printStackTrace();
 49         }
 50         try {
 51             t.process(dataMap, out);
 52         } catch (TemplateException e) {
 53             e.printStackTrace();
 54         } catch (IOException e) {
 55             e.printStackTrace();
 56         }
 57     }
 58 
 59     public byte[] getBytesFromFile(File f) {
 60         if (f == null) {
 61             return null;
 62         }
 63         try {
 64             FileInputStream stream = new FileInputStream(f);
 65             ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
 66             byte[] b = new byte[1000];
 67             int n;
 68             while ((n = stream.read(b)) != -1)
 69                 out.write(b, 0, n);
 70             stream.close();
 71             out.close();
 72             return out.toByteArray();
 73         } catch (IOException e) {
 74             e.printStackTrace();
 75         }
 76         return null;
 77     }
 78 }
 79 
 80 
 81 class ByteArrayStreamTemplateLoader implements TemplateLoader {
 82 
 83     InputStream in = null;
 84 
 85     public ByteArrayStreamTemplateLoader(ByteArrayInputStream inputStream) {
 86         in = inputStream;
 87     }
 88 
 89     public Object findTemplateSource(String name) throws IOException {
 90         System.out.println("findTemplateSource");
 91         return in;
 92     }
 93 
 94     public long getLastModified(Object templateSource) {
 95         return 0;
 96     }
 97 
 98     public Reader getReader(Object templateSource, String encoding) throws IOException {
 99         System.out.println("getReader");
100         return new InputStreamReader(in);
101     }
102 
103     public void closeTemplateSource(Object templateSource) throws IOException {
104         System.out.println("closeTemplateSource");
105         if (in != null) {
106             in.close();
107         }
108     }
109 }
posted @ 2011-09-01 09:17  阿兹猫  阅读(10548)  评论(0编辑  收藏  举报