java 如何将word 转换为ftl_使用 freemarker导出word文档

近日需要将人员的基本信息导出,存储为word文档,查阅了很多资料,最后选择了使用freemarker,网上一共有四种方式,效果都一样,选择它呢是因为使用简单,再次记录一下,一个简单的demo,仅供参考。

1.引入依赖:

org.freemarker

freemarker

2.3.20

2.word工具类

package com.bfd.bose_kotwalee_screen_data.util.word;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStreamWriter;

import java.io.Writer;

import java.net.URLEncoder;

import java.util.Date;

import java.util.Map;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;

import freemarker.template.Template;

import freemarker.template.utility.DateUtil;

import org.apache.directory.api.util.DateUtils;

public class WordUtils {

private static Configuration configuration = null;

//class.getResource()可以获取绝对路径和相对路径

private static final String templateFolder = WordUtils.class.getResource("/templates").getPath();

static {

configuration = new Configuration();

configuration.setDefaultEncoding("utf-8");

try {

configuration.setDirectoryForTemplateLoading(new File(templateFolder));

} catch (IOException e) {

e.printStackTrace();

}

}

private WordUtils() {

throw new AssertionError();

}

public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws IOException {

Template freemarkerTemplate = configuration.getTemplate(ftlFile);

File file = null;

InputStream fin = null;

ServletOutputStream out = null;

try {

// 调用工具类的createDoc方法生成Word文档

file = createDoc(map, freemarkerTemplate);

fin = new FileInputStream(file);

response.setCharacterEncoding("utf-8");

response.setContentType("application/msword");

// 设置浏览器以下载的方式处理该文件名 + DateUtils.getDate("2019-08-29")

String fileName = title + ".doc";

response.setHeader("Content-Disposition", "attachment;filename="

.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

out = response.getOutputStream();

byte[] buffer = new byte[512]; // 缓冲区

int bytesToRead = -1;

// 通过循环将读入的Word文件的内容输出到浏览器中

while ((bytesToRead = fin.read(buffer)) != -1) {

out.write(buffer, 0, bytesToRead);

}

} finally {

if (fin != null) {

fin.close();

}

if (out != null) {

out.close();

}

if (file != null) {

file.delete(); // 删除临时文件

}

}

}

private static File createDoc(Map, ?> dataMap, Template template) {

String name = "sellPlan.doc";

File f = new File(name);

Template t = template;

try {

// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开

Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");

t.process(dataMap, w);

w.close();

} catch (Exception ex) {

ex.printStackTrace();

throw new RuntimeException(ex);

}

return f;

}

}

3.service代码

public void exportSellPlan(HttpServletRequest request, HttpServletResponse response) {

Calendar calendar = Calendar.getInstance();// 取当前日期。

//图片地址

String imagePath = WordUtils.class.getResource("/img").getPath()+"/test.jpg";

//获得数据

Map map = new HashMap<>();

List> list = new ArrayList<>();

Map m;

for (int i = 0;i<3;i++){

m = new HashMap<>();

m.put("name","张三" + i);

m.put("age","" + 13 + i);

list.add(m);

}

map.put("list",list);

map.put("img",this.getImageBase(imagePath));

try {

//table.ftl为word模板

WordUtils.exportMillCertificateWord(request, response, map, "简历方案", "table.ftl");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//获得图片的base64码

@SuppressWarnings("deprecation")

public String getImageBase(String src) {

if(src==null||src==""){

return "";

}

File file = new File(src);

if(!file.exists()) {

return "";

}

InputStream in = null;

byte[] data = null;

try {

in = new FileInputStream(file);

} catch (FileNotFoundException e1) {

e1.printStackTrace();

}

try {

data = new byte[in.available()];

in.read(data);

in.close();

} catch (IOException e) {

e.printStackTrace();

}

BASE64Encoder encoder = new BASE64Encoder();

return encoder.encode(data);

}

4.模板制作

1)制作word模板,另存为.xml文件

d428c04d05b6

image.png

2)将.xml文件上传到工程中,并修改为.ftl后缀

d428c04d05b6

image.png

这个路径在下面这行代码设定

private static final String templateFolder = WordUtils.class.getResource("/templates").getPath();

完成以上步骤,导出word功能就完成了。

注意:制作模板的时候,${name}绑定字段的时候在.ftl文件或被默认拆分,需要手动修改一下。封装数据的时候要和模板一一对应,数据为空的话也要添加,模板中的字段名在封装的数据必须有。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388770.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

DotNetBar office2007效果

1.DataGridView 格式化显示cell里的数据日期等。 进入编辑列&#xff0c;选择要设置的列&#xff0c;DefaultCellStyle里->行为->formart设置 2.tabstrip和mdi窗口的结合使用给MDI窗口加上TabPage。拖动个tabstrip到MDI窗口上tabstrip里选择到主窗口名就加上TABPAGE了。d…

Spring boot 中pom.xml 各个节点详解

<project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <!-- 父项目的坐…

spotify 数据分析_没有数据? 没问题! 如何从Wikipedia和Spotify收集重金属数据

spotify 数据分析For many data science students, collecting data is seen as a solved problem. It’s just there in Kaggle or UCI. However, that’s not how data is available daily for working Data Scientists. Also, many of the datasets used for learning have …

stack 的一些用法

#include<bits/stdc.h> using namespace std; int32_t main() {stack<int> st;st.push(1);st.push(2);st.push(3);cout<<st.size()<<endl;while(!st.empty()){cout<<st.top()<<endl;st.pop();} } 转载于:https://www.cnblogs.com/Andromed…

IS环境下配置PHP5+MySql+PHPMyAdmin

IIS环境下配置PHP5MySqlPHPMyAdmin Posted on 2009-08-07 15:18 谢启祥 阅读(1385)评论(18) 编辑 收藏 虽然主要是做.net开发的&#xff0c;但是&#xff0c;时不时的还要搞一下php&#xff0c;但是&#xff0c;php在windows下的配置&#xff0c;总是走很多弯路&#xff0c;正好…

js复制功能

<div id"cardList"><div class"btn" onClick"copy(111)">点击我&#xff0c;复制我</div></div> <script type"text/javascript"> function copy(str){var save function (e){e.clipboardData.setDa…

input在iOS里的兼容性

input框在iOS里&#xff0c;无法聚焦&#xff0c;不能输入内容&#xff0c;把-webkit-user-select:none改成-webkit-user-select:auto;或者直接加一个style“-webkit-user-select:auto”.

kaggle数据集_Kaggle上有170万份ArXiv文章的数据集

kaggle数据集“arXiv is a free distribution service and an open-access archive for 1.7 million scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and sys…

java用接口实例化对象_[求助]迷茫中,接口可以直接实例化对象吗?

可能是我没有写完整吧,还是我没有理解好1 接口public interface SetAndGetWeight{public void setW(double weight);public double getW();}2 类class Train{SetAndGetWeight[] things;public void Train(SetAndGetWeight[] things){this.thingsthings;}public void returnTota…

异常作业2(2018.08.22)

2、编写程序接收用户输入分数信息&#xff0c;如果分数在0—100之间&#xff0c; 输出成绩。如果成绩不在该范围内&#xff0c; 抛出异常信息&#xff0c;提示分数必须在0—100之间。 要求&#xff1a;使用自定义异常实现1 import java.util.Scanner;2 3 class AtException ext…

深度学习数据集中数据差异大_使用差异隐私来利用大数据并保留隐私

深度学习数据集中数据差异大The modern world runs on “big data,” the massive data sets used by governments, firms, and academic researchers to conduct analyses, unearth patterns, and drive decision-making. When it comes to data analysis, bigger can be bett…

C#图片处理基本应用(裁剪,缩放,清晰度,水印)

前言 需求源自项目中的一些应用&#xff0c;比如相册功能&#xff0c;通常用户上传相片后我们都会针对该相片再生成一张缩略图&#xff0c;用于其它页面上的列表显示。随便看一下&#xff0c;大部分网站基本都是将原图等比缩放来生成缩略图。但完美主义者会发现一些问题&#…

java建立tcp服务器长连接_B/S 架构下后端能否建立 TCP 长连接?

这种架构下&#xff0c;这样的优化策略能实现吗&#xff1f;能有作用吗&#xff1f;php 服务端请求 ES tcp server 部分代码$streamClient stream_socket_client("tcp://{$tcpHost}:{$tcpPort}", $errno, $errstr);// 该数组是所有业务线的分类结构&#xff0c;及每…

Java客户端访问HBase集群解决方案(优化)

测试环境&#xff1a;IdeaWindows10 准备工作&#xff1a; <1>、打开本地 C:\Windows\System32\drivers\etc&#xff08;系统默认&#xff09;下名为hosts的系统文件&#xff0c;如果提示当前用户没有权限打开文件&#xff1b;第一种方法是将hosts文件拖到桌面进行配置后…

WPF布局系统

WPF之路——WPF布局系统 前言 前段时间忙了一阵子Google Earth&#xff0c;这周又忙了一阵子架构师论文开题报告&#xff0c;现在终于有时间继续<WPF之路>了。先回忆一下上篇的内容&#xff0c;在《从HelloWorld到WPF World》中&#xff0c;我们对WPF有了个大概的了解&am…

PostGIS容器运行

2019独角兽企业重金招聘Python工程师标准>>> 获取镜像&#xff1a; docker pull mdillon/postgis 该 mdillon/postgis 镜像提供了容器中运行Postgres&#xff08;内置安装PostGIS 2.5&#xff09; 。该镜像基于官方 postgres image&#xff0c;提供了多种变体&#…

小型数据库_如果您从事“小型科学”工作,那么您是否正在利用数据存储库?

小型数据库If you’re a scientist, especially one performing a lot of your research alone, you probably have more than one spreadsheet of important data that you just haven’t gotten around to writing up yet. Maybe you never will. Sitting idle on a hard dri…

BitmapEffect位图效果是简单的像素处理操作。它可以呈现下面几种特殊效果。

BitmapEffect位图效果是简单的像素处理操作。它可以呈现下面几种特殊效果。 BevelBitmapEffect 凹凸效果 BlurBitmapEffect 模糊效果 DropShadowBitmapEffect投影效果 EmbossBitmapEffect 浮雕效果 Outer…

AutoScaling 与函数计算结合,赋予更丰富的弹性能力

目前&#xff0c;弹性伸缩服务已经接入了负载均衡&#xff08;SLB&#xff09;、云数据库RDS 等云产品&#xff0c;但是暂未接入 云数据库Redis&#xff0c;有时候我们可能会需要弹性伸缩服务在扩缩容的时候自动将扩缩容涉及到的 ECS 实例私网 IP 添加到 Redis 白名单或者从 Re…

参考文献_参考

参考文献Recently, I am attracted by the news that Tanzania has attained lower middle income status under the World Bank’s classification, five years ahead of projection. Being curious on how they make the judgement, I take a look of the World Bank’s offi…