简要步骤
1、首先需要准备一个word模板,样式都可以在office上设置好,在需要填入值得地方用 ${name}的方式填充。
2、将准备好的word模板另存为 .xml 格式的文件,然后将其后缀名改为 .ftl 。文件打开后如下图
3、将word模板和.fil文件可以放在服务器上指定的地方,位置可以自定义。
相关代码如下
Java代码(向模板中写入数据):
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
private void wordOutput(Map<String, Object> dataMap, String sourceName, String targetPath, String
tempaltePath) {
try {
// Configuration 用于读取ftl文件
Configuration configuration = new Configuration(new Version("2.3.23"));
configuration.setDefaultEncoding("utf-8");
String resourcesPath = tempaltePath;
// 处理路径中的中文乱码问题
String path = URLDecoder.decode(resourcesPath, "utf-8");
System.out.println(path);
configuration.setDirectoryForTemplateLoading(new File(path));
// 输出文档路径及名称
File outFile = new File(targetPath);
// 以utf-8的编码读取ftl文件
Template template = configuration.getTemplate("柯桥区技术合作拟奖励项目专家评审意见表.ftl", "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
template.process(dataMap, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
每次写入数据都会覆盖掉之前的数据,最后下载改模板即可。
文件下载工具类
public void downloadfile(HttpServletRequest request, HttpServletResponse response, String filePath) {
File file = new File(filePath);
String fileName = file.getName();
InputStream fis = null;
try {
fis = new FileInputStream(file);
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0) || ((agent.contains("RV")) && (!agent.contains("FIREFOX"))))
fileName = URLEncoder.encode(fileName, "UTF-8");
else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
response.flushBuffer();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
——内容仅供参考