准备工作:
1、xml模版,获取方式为docx文件winrar方式打开,取出document.xml
2、将内容格式化后修改需要替换的内容为freemarker标签,如下:
3、文件准备好后存放到某个目录下,docx文件为将要生成好的docx文件样式模版,必须要有的。
4、准备程序代码
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) {
//模版文件存放目录
String templatepath = "E:/test/";
//模版样式文件名
String docxname = "document.docx";
//模版xml文件
String xmlname = "document.xml";
//替换freemarker标签后的临时xml文件
String tmpxmlpath = "E:/test/temp.xml";
//最终生成的docx文件
String targetpath = "E:/test/final.docx";
// 数据
Map<String,Object> data = new HashMap();
data.put("summary","这里是替换的文字");
// 生成文档
try {
outputWord(templatepath, docxname, xmlname, tmpxmlpath, targetpath, data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description 根据参数生成docx合同文档
* @author HubertToLee
* @param templatepath 模板所在文件夹
* @param docxname docx格式模板文件名(不带路径)
* @param xmlname xml格式模板,有freemaker标记(不带路径)
* @param tmpxmlpath 临时xml文件路径
* @param targetPath 目标文件路径
* @param param 待填充数据
* @return
* @throws Exception
*/
private static boolean outputWord(String templatepath, String docxname, String xmlname,
String tmpxmlpath, String targetPath, Map<String, Object> param) throws Exception {
//-------------start-----------------
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(templatepath));
//以UTF-8的编码格式读入文件
Template template = cfg.getTemplate(xmlname,"UTF-8");
//以UTF-8的编码格式输出文件
template.setOutputEncoding("UTF-8");
Writer out = new FileWriter(new File(tmpxmlpath));
// 数据放到模板xml里面,生成带数据的xml
template.process(param, out);
if (out != null) {
out.close();
}
//-------------end-----------------
//以上这块代码目的只为生替换freemarker标签后的xml文件
//实际开发中,也可以用替换后的字符串生成xml文件来生成word
File file = new File(tmpxmlpath);
File docxFile = new File(templatepath + "/" + docxname);
ZipFile zipFile = new ZipFile(docxFile);
Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(targetPath));
int len = -1;
byte[] buffer = new byte[1024];
while (zipEntrys.hasMoreElements()) {
ZipEntry next = zipEntrys.nextElement();
InputStream is = zipFile.getInputStream(next);
// 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
zipout.putNextEntry(new ZipEntry(next.toString()));
if ("word/document.xml".equals(next.toString())) {
InputStream in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
in.close();
} else {
while ((len = is.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
is.close();
}
}
zipout.close();
return true;
}
}
关于字符串转换成xml文件,大家可以看我上篇文章,点击直达
版权声明:本文为HubertToLee原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。