关于使用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 ...
随机推荐
- 关于Java中static关键字的用法以及从内存角度解析
在Java中,static可以用来修饰成员变量和成员方法. 修饰成员变量,称为静态成员方法 修饰静态方法,称为静态成员方法 搞清楚用法和区别之前,先搞清static声明的变量和普通非静态变量在内存的分 ...
- Widows自带系统监控工具——24小时监控服务器性能
博文来源:https://blog.csdn.net/qq_41650233/article/details/84313153 操作步骤1.运行程序perfmon.exe 2.在数据收集器下选择[用户 ...
- Loadrunner测试数据库性能,测试SQL语句的脚本例子
Loadrunner与SQL Server的操作可以通过录制的方式来实现,但本文还是通过直接调用loadrunner本身的function来实现sql语句的操作, 主要用到的是lr_db_connec ...
- 论文阅读笔记四十九:ScratchDet: Training Single-Shot Object Detectors from Scratch(CVPR2019)
论文原址:https://arxiv.org/abs/1810.08425 github:https://github.com/KimSoybean/ScratchDet 摘要 当前较为流行的检测算法 ...
- python+selenium自动测试之WebDriver的常用API(基础篇一)
基于python3.6,selenium3.141,详细资料介绍查看官方API文档,点击这里 一.对浏览器操作 driver = webdriver.Chrome() # 初始化chrome driv ...
- hackerrank杂记
https://www.hackerrank.com/challenges/py-set-discard-remove-pop/forum 知识点: *list:将list中的值取出,取出的数据大小是 ...
- SpringMVC源码分析-400异常处理流程及解决方法
本文涉及SpringMVC异常处理体系源码分析,SpringMVC异常处理相关类的设计模式,实际工作中异常处理的实践. 问题场景 假设我们的SpringMVC应用中有如下控制器: 代码示例-1 @Re ...
- redis安装使用
Redis是一个开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API. 它通常被称为数据结构服务器,因为值(valu ...
- FSBPM 开发过程中一些提醒备注信息(供参考)
------智能OA系统开发过程中 前端开发前端 搜索查询的配置 运算操作符: like equals 共两种筛选数据方式. html标签上配置一下eg: <inpu ...
- js中的传值和传引用,判断两个数组是否相等
所谓js的中的传值,其实也就是说5种基本数据类型(null,undefind,boolean,number,string) 传引用也就是说的那个引用数据类型,(array和objec) 基本数据类型的 ...