关于使用freemarker导出文档的使用
7、FreeMarker导出word文件,模板:template.ftl
/**
* 为word加载数据插值
*
* @throws IOException
*/
public void exportWord() throws IOException {
/** 用于组装word页面需要的数据 */
Map<String, Object> dataMap = new HashMap<String, Object>();
HttpServletRequest request = ServletActionContext.getRequest();
QueryParamList param = new QueryParamList();
param.addParam("customerNo", customerCode);
List<Customer> list = JPAUtil.load(Customer.class, param);
String customerName = list.get(0).getCustomerName();
String reportMonth = request.getParameter("month");
/** 组装数据 */
dataMap.put("xxxtitle", customerName + reportMonth.substring(0, 4)
+ "年" + reportMonth.substring(5, 7) + "月运行分析情况");
String imgData = request.getParameter("imgData");
String fileStr = "";
try {
String[] url = imgData.split(",");
String u = url[1];
// Base64解码
byte[] b = new BASE64Decoder().decodeBuffer(u);
fileStr = saveFile();
// 生成图片
OutputStream out = new FileOutputStream(new File(fileStr
+ "\\elecQChart.png"));
out.write(b);
out.flush();
out.close();
String jpgFile = ConvertJpgFile(fileStr + "\\elecQChart.png");
File file = new File(fileStr + "\\elecQChart.png");
file.delete();
dataMap.put("elecQChart", getImageStr(jpgFile));
} catch (Exception e) {
e.printStackTrace();
}
List<Map<String, Object>> elecQList = new ArrayList<Map<String, Object>>();
for (int i = 1; i <= 3; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "110KV高压进线");
map.put("totalQ", "13351536");
map.put("fQ", "4435992");
map.put("pQ", "4545112");
map.put("gQ", "4370432");
map.put("jQ", "0");
map.put("fQr", "30%");
map.put("pQr", "30%");
map.put("gQr", "30%");
map.put("jQr", "0");
elecQList.add(map);
}
dataMap.put("elecQList", elecQList);
List<Map<String, Object>> elecFactor = new ArrayList<Map<String, Object>>();
for (int i = 1; i <= 3; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "10KV制冷机");
map.put("active", "69");
map.put("idle", "64");
map.put("fac", "0.92");
elecFactor.add(map);
}
dataMap.put("elecFactor", elecFactor);
List<Map<String, Object>> transf = new ArrayList<Map<String, Object>>();
for (int i = 1; i <= 3; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "10KV制冷机");
map.put("avgP", "69.72");
map.put("maxP", "87");
map.put("avgPr", "91");
transf.add(map);
}
dataMap.put("transf", transf);
List<Map<String, Object>> thrPhaUnb = new ArrayList<Map<String, Object>>();
for (int i = 1; i <= 3; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "10KV制冷机");
map.put("Ia", "69.72");
map.put("Ib", "65");
map.put("Ic", "69.72");
map.put("Iz", "87.6");
map.put("Uab", "201");
map.put("Ubc", "210");
map.put("Uca", "210");
map.put("Ir", "87.6");
map.put("Ur", "67.6");
thrPhaUnb.add(map);
}
dataMap.put("thrPhaUnb", thrPhaUnb);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
/** 文件名称,唯一字符串 */
String fileName = "电量月报表" + sdf.format(cal.getTime()) + ".doc";
try {
/** 生成word */
createDoc(dataMap, fileName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* 从服务器获取echart图片
*
* @param imgFile
* @return
*/
public String getImageStr(String imgFile) {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 删除临时文件
File file = new File(imgFile);
file.delete();
return encoder.encode(data);
}
/**
* 保存echart图片到服务器
*
* @return
*/
public String saveFile() {
String nowpath = System.getProperty("user.dir");
String path = nowpath.replace("bin", "webapps");
File tmp = new File(path);
if (!tmp.exists()) {
tmp.mkdirs();
}
return path;
}
/**
* 根据ftl模板创建word文件
*
* @param dataMap
* @param fileName
* @throws IOException
*/
public void createDoc(Map<String, Object> dataMap, String fileName)
throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
// dataMap 要填入模本的数据文件
// 设置模本装置方法和路径,模板是放在action包下面
// 创建配置实例
@SuppressWarnings("deprecation")
Configuration configuration = new Configuration();
// 设置编码
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(this.getClass(),
"/com/haiyisoft/iecp/monitor/action");
Template t = null;
try {
// temp.ftl为要装载的模板
t = configuration.getTemplate("template.ftl");
} catch (IOException e) {
e.printStackTrace();
}
// 获取桌面路径
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath();
desktopPath = desktopPath.replace("\\", "/");
// 输出文档路径及名称
File outFile = new File(desktopPath + "/" + fileName);
Writer out = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter outW = response.getWriter();
outW.write("导出成功!</br>" + outFile.getPath());
outW.close();
}
/**
* png图片转成JPG格式
*
* @param fileName
* @return
*/
public String ConvertJpgFile(String fileName) {
String jpgFile = fileName.substring(0, fileName.length() - 4) + ".jpg";
BufferedImage bufferedImage;
try {
// 读取图片文件
bufferedImage = ImageIO.read(new File(fileName));
// 创建图片背景,大小
BufferedImage newBufferedImage = new BufferedImage(
bufferedImage.getWidth(), bufferedImage.getHeight(),
BufferedImage.TYPE_INT_RGB);
// TYPE_INT_RGB:创建一个RBG图像,24位深度,成功将32位图转化成24位
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0,
Color.WHITE, null);
// 写入JPG图片
ImageIO.write(newBufferedImage, "jpg", new File(jpgFile));
} catch (IOException e) {
e.printStackTrace();
}
return jpgFile;
}
/**
* 根据ftl模板创建Excel文件
*
* @param dataMap
* @param fileName
* @throws IOException
*/
@SuppressWarnings("deprecation")
public void createExcel1(Map<String, Object> dataMap, String fileName) throws IOException {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
// dataMap 要填入模本的数据文件
// 设置模本装置方法和路径,模板是放在action包下面
// 创建配置实例
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置编码
cfg.setDefaultEncoding("UTF-8");
cfg.setClassForTemplateLoading(this.getClass(), "/com/haiyisoft/iecp/monitor/action");
Properties prop = System.getProperties();
String osName = prop.getProperty("os.name");
String separator = prop.getProperty("file.separator");
System.out.println(osName + "文件目录分隔符:" + separator);
// 获取deploy下download路径
String urlStr = request.getRealPath("/") + "download\\";
urlStr = urlStr.replace("\\", "/");
// 输出文档路径及名称
File outFile = new File(urlStr + "/" + fileName);
Writer out = null;
FileOutputStream fos = null;
Template t = null;
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter outW = response.getWriter();
try {
// temp.ftl为要装载的模板
t = cfg.getTemplate("excelTemplate.ftl");
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
out = new BufferedWriter(oWriter);
t.process(dataMap, out);
out.close();
fos.close();
System.out.println("文件在服务deploy下的路径:" + outFile.getPath());
outW.write(separator + "#" + outFile.getPath());
outW.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
public void createExcel(Map<String, Object> dataMap, String fileName) throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
// dataMap 要填入模本的数据文件
// 设置模本装置方法和路径,模板是放在action包下面
// 创建配置实例
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置编码
cfg.setDefaultEncoding("UTF-8");
cfg.setClassForTemplateLoading(this.getClass(), "/com/haiyisoft/iecp/monitor/action");
Properties prop = System.getProperties();
String osName = prop.getProperty("os.name");
String separator = prop.getProperty("file.separator");
System.out.println(osName + "文件目录分隔符:" + separator);
// 获取deploy下download路径
String urlStr = request.getRealPath("/") + "download\\";
urlStr = urlStr.replace("\\", "/");
// 输出文档路径及名称
File outFile = new File(urlStr + "/" + fileName);
Writer writer = null;
FileOutputStream fos = null;
Template t = null;
PrintWriter outW = response.getWriter();
try {
// temp.ftl为要装载的模板
t = cfg.getTemplate("excelTemplate.ftl");
fos = new FileOutputStream(outFile);
writer = new OutputStreamWriter(fos, "UTF-8");
t.process(dataMap, writer);
writer.close();
fos.close();
System.out.println("文件在服务deploy下的路径:" + outFile.getPath());
outW.write(separator + "#" + outFile.getPath());
outW.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
/**
* 删除临时文件
*/
public void delTempFile() {
HttpServletRequest request = ServletActionContext.getRequest();
String path = request.getParameter("path");
File file = new File(path);
file.delete();
}
关于使用freemarker导出文档的使用的更多相关文章
- qt 工具下的dump工具导出文档出现异常解决方案
今天一直认为qt环境下的dumpcpp 和dumpdoc两个导出工具很好用,可以今天在导出MSChart组件的类方法文档时,虽然导出成功了,但是导出的结果却是令人失望.自己也不知道如何能够正确导出,就 ...
- Freemarker全部文档和具体实例
自己查找到了一些相关的资料分享给大家,有兴趣的可以去看看! Freemarker全部文档:http://www.open-open.com/doc/list/101?o=p
- 基于.NetCore3.1搭建项目系列 —— 使用Swagger导出文档 (补充篇)
前言 在上一篇导出文档番外篇中,我们已经熟悉了怎样根据json数据导出word的文档,生成接口文档,而在这一篇,将对上一篇进行完善补充,增加多种导出方式,实现更加完善的导出功能. 回顾 1. 获取Sw ...
- freemarker导出word档
1.word另存为xml:2.xml文件后缀名改成ftl:3.编写完整json字符串备用:4.修改ftl中动态字段为json中对应字段名:5.编写java代码自动生成word文件:(注意:换行用< ...
- 基于.NetCore3.1搭建项目系列 —— 使用Swagger导出文档 (番外篇)
前言 回顾之前的两篇Swagger做Api接口文档,我们大体上学会了如何在net core3.1的项目基础上,搭建一套自动生产API接口说明文档的框架. 本来在Swagger的基础上,前后端开发人员在 ...
- 常用freemarker使用文档
设置价格格式 <#setting number_format = "currency" /> <#assign price = 42 /> ${price} ...
- POI 导出文档整理
1 通过模板获取workbook public static Workbook getWorkBook(String templatePath) { try { InputStream in = ne ...
- 导出文档设置exportDocument
<?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4" ...
- unieap 导出文档错误
java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalCon ...
随机推荐
- postgresql分析函数
参考:https://blog.csdn.net/haohaizijhz/article/details/83340814 SELECT uid, odate, num, sum(num) over ...
- C# 最全的文件工具类FileHelper
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...
- 常见jquery面试题
jQuery 面试问题和答案 JavaScript 是客户端脚本的标准语言,而 jQuery 使得编写 JavaScript 更加简单.你可以只用写几行的jQuery 代码就能实现更多的东西. 它是最 ...
- syntax error near unexpected token `do(写的shell脚本出现格式问题)--->1.问题2.展示信息3.解决方案
1问题:Linux和windows下的回车换行符不兼容的问题 [root@node-01 script]# sh start_zk.sh art_zk.sh: line 3: syntax error ...
- 部署lamp动态网站(图解)
环境拓扑如下:1.两台虚拟机要互通 2.修改selinux +++++++++++++++++++++++++++服务器133上: 1.安装需要的组件httpd,mariadb,php 2 ...
- open suse 42.3常用软件源(包括阿里云)
阿里镜像源,直接在终端安装,首先在终端输入 su 点击回车,输入密码,密码输入时为了安全是不显示的,你输入以后直接回车就可以了. zypper addrepo -f http://mirrors.al ...
- 微信域名检测的C#实现
背景:最近公司的公众号域名被封了,原因是公司网站被黑后上传了一个不符合微信规范的网页.所以...就进入了微信域名解封的流程. 百度微信域名解封发现很多微信域名检测的网站,还有Api:但是本人做微信公 ...
- python案例——体脂率项目
通过一个人的身高.体重.年龄.性别,判断这个人的体脂率,并且反馈是否正常? 首先接到项目后一定要一步步细分任务,直到每个细分的任务都可以用代码来实现. 写代码之前,先要确定python版本的问题 然后 ...
- 2018-2019 20165239 Exip MSF基础应用
实践内容(3.5分) 本实践目标是掌握metasploit的基本应用方式,重点常用的三种攻击方式的思路.具体需要完成: 1.1一个主动攻击实践,如ms08_067; (1分) 1.2 一个针对浏览器的 ...
- js,JQ 图片转换base64 base64转换为file对象,blob对象
//将图片转换为Base64 function getImgToBase64(url,callback){ var canvas = document.createElement('canvas'), ...