您的位置:首页 > 编程语言 > Java开发

java根据word模板导出word文件

2016-06-27 10:39 423 查看
1、word模板文件处理,如下图所示在word 文档中填值的地方写入占位变量



2、将word文档另存为xml文件、编辑如下图,找到填写的占位,修改为${bcrxm}格式



3、将文件后缀名改为.ftl文件

4、java处理过程 、 引入frameMark jar 包



5、java代码

  一、将需要填充的数据封装到map中、与模板中的占位对应、为什么用map 我也不知道。

  二、创建configuration对象

  三、设置编码 utf-8

  四、获取模板 configuration.setDirectoryForTemplateLoading() 方法、configuration.getTemplate()方法

  五、将模板和数据模型合并生成文件 template.process(map, out); //map为封装的数据、out为输出流对象

6、完整代码、configuration.setClassForTemplateLoading 方法有不同的使用方式、可以根据自己的需要选择、具体使用方法、问度娘。

public static  String createWord1(Map dataMap,String templateName,String filePath,String fileName,HttpServletRequest request,HttpServletResponse response){
String    fileOnlyName=null;
try {
//创建配置实例
Configuration configuration = new Configuration();

//设置编码
configuration.setDefaultEncoding("UTF-8");

//ftl模板文件统一放至 template 包下面
configuration.setClassForTemplateLoading(Util.class,"/template/");

//获取模板
Template template = configuration.getTemplate(templateName,"UTF-8");
//重命名
fileOnlyName = rename(fileName);
//定义路径 统一放到 webappo/hgjc/uploadRoot目录下
String servicePath = request.getSession().getServletContext().getRealPath(File.separator);
String basePath = ReadConfig.getConfigValue("uploadRoot")+File.separator+ReadConfig.getConfigValue(filePath)+File.separator+fileOnlyName;
//输出文件
File outFile = new File(servicePath+basePath);

//如果输出目标文件夹不存在,则创建
if (!outFile.getParentFile().exists()   ){
outFile.getParentFile().mkdirs();
}

//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));

//生成文件
template.process(dataMap, out);
//关闭流
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileOnlyName;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: