由于最近工作需要使用java代码生成多样化格式的word文档,第一个想到了xml来实现,在网上找了几个例子再结合自己的项目需求,最终实现了想要的效果。
具体的思路是:
1、将要生成的word文档(我这里使用的是word2003版本)内需要替换的动态写入的内容替换成公式(例如:$test)。如下图:
2、将word文档另存为xml格式,另存的时候要注意版本
3、将生成的xml文档拷贝至一个空的word文档内部,保存该新的word文档。
4、将保存的word文档存储至数据库blob字段。
5、在程序运行的时候可以将存储的xml内容的word文档读取出来,获取到xml内容的字符串,对内容公式进行替换。获取到替换内容之后的xml字符串。
6、下面开始使用freemarker对xml字符串进行处理,生成我们想要的word文档。
关键代码如下:
/**
* 方法说明: 根据前台传递的xml格式模板生成word文件并将doc的byte[]内容存储至数据库
* (也可以根据指定路径的xml格式文件模板来生成,具体查看freeMarker API doc)
* @param sTemplateXML 前台传递过来的xml格式doc模板文件
* @throws Exception
*/
public void onCreateSaveDoc(String sTemplateXML)
{
String sDocName = "";
FileInputStream inputStreamSave = null;
ByteArrayOutputStream outSave = null;
Writer out = null;
try
{
sDocName = "test.doc";
Configuration configure = new Configuration();
configure.setDefaultEncoding("utf-8");
//加载需要装填的模板
Template template = null;
//设置对象包装器
configure.setObjectWrapper(new DefaultObjectWrapper());
//设置异常处理器
configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
StringTemplateLoader stringLoader = new StringTemplateLoader();
//加载模板文件
stringLoader.putTemplate("docTemplate", sTemplateXML);
configure.setTemplateLoader(stringLoader);
template = configure.getTemplate("docTemplate","utf-8");
//指定服务器存储临时文件的文件夹
String path = this.getClass().getClassLoader().getResource("/").getPath();
String configPath = path.replaceAll("/WEB-INF/classes/", "/docTemp/"); //适用于webLogic上传文件至war包下
// ***创建服务器存放上传文件的文件夹,没有则创建***
File file = new File(configPath);
if (!file.exists())
{
file.mkdirs();
}
String sDocPath = configPath + "/" + sDocName;
//输出文档
File uploadFile = new File(sDocPath);//这里是生成好的word文档的输出地址
out = null;
out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(uploadFile),"utf-8"));
template.process(null,out);
uploadFile.delete();
out.close();
}
catch (Exception e)
{
e.printStacktrace();
}
finally
{
out.close();
}
}