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导出文档的使用的更多相关文章

  1. qt 工具下的dump工具导出文档出现异常解决方案

    今天一直认为qt环境下的dumpcpp 和dumpdoc两个导出工具很好用,可以今天在导出MSChart组件的类方法文档时,虽然导出成功了,但是导出的结果却是令人失望.自己也不知道如何能够正确导出,就 ...

  2. Freemarker全部文档和具体实例

    自己查找到了一些相关的资料分享给大家,有兴趣的可以去看看! Freemarker全部文档:http://www.open-open.com/doc/list/101?o=p

  3. 基于.NetCore3.1搭建项目系列 —— 使用Swagger导出文档 (补充篇)

    前言 在上一篇导出文档番外篇中,我们已经熟悉了怎样根据json数据导出word的文档,生成接口文档,而在这一篇,将对上一篇进行完善补充,增加多种导出方式,实现更加完善的导出功能. 回顾 1. 获取Sw ...

  4. freemarker导出word档

    1.word另存为xml:2.xml文件后缀名改成ftl:3.编写完整json字符串备用:4.修改ftl中动态字段为json中对应字段名:5.编写java代码自动生成word文件:(注意:换行用< ...

  5. 基于.NetCore3.1搭建项目系列 —— 使用Swagger导出文档 (番外篇)

    前言 回顾之前的两篇Swagger做Api接口文档,我们大体上学会了如何在net core3.1的项目基础上,搭建一套自动生产API接口说明文档的框架. 本来在Swagger的基础上,前后端开发人员在 ...

  6. 常用freemarker使用文档

    设置价格格式 <#setting number_format = "currency" /> <#assign price = 42 /> ${price} ...

  7. POI 导出文档整理

    1 通过模板获取workbook public static Workbook getWorkBook(String templatePath) { try { InputStream in = ne ...

  8. 导出文档设置exportDocument

    <?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4" ...

  9. unieap 导出文档错误

    java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalCon ...

随机推荐

  1. 关于tarjan

    关于Tarjan算法 梗概 tarjan算法有两种(我了解的),一种是用来求强连通分量的,另一种是关于割点和桥的问题. 根据机房大佬HL说过,这两种算法是互相独立的,只是代码很像. 强连通分量问题 关 ...

  2. #10038.A Horrible Poem

    #10038.A Horrible Poem 题目传送门 思路解析 既然这道题目在hash板块里,那么自然就可以想到用hash做这道题目. 首先我们可以用hash数组存储字符串的前缀的hash值. 因 ...

  3. MapReduce流量统计

    准备数据access.log 要用到的只有第二个手机号,倒数第三上行流量,倒数第二下行流量. 1363157985066 13726230503 00-FD-07-A4-72-B8:CMCC 120. ...

  4. 预制体,Mask组件

    1.预制体制作和使用 a.制作预制体,将制作好的元素插入到在文件夹下形成一个预制体 b.将预制体在所调用的脚本文件中进行声明,并且在界面里进行拖入保存 c.使用的时候利用cc.instantiate进 ...

  5. linux 服务器常用命令整理

    linux 服务器常用命令整理 目录 网络分析 - tcpdump \ telnet \ (netstat \ ss \ lsof) \ nload 网络传输 - scp \ rsync \ (rz ...

  6. Outlook IMAP 修改PST文件存储路径

    IMAP类型的账户修改PST文件位置方法: 对于IMAP类型账户的PST文件,既没有“修改文件夹”的选项,也无法按OFFICE官方操作指南中的操作.因为每次Outlook只要检测到默认路径下的PST文 ...

  7. hbase_1

    常见的RDBMS:(数据库排行) ** mysql --开源[社区版] .收费[企业版] --市场占有率高.web领域被广泛使用 ** 2008年被oracle收购 ** mysql主从架构[集群的一 ...

  8. 如何编写高效的jQuery代码(转载)

    jQuery的编写原则: 一.不要过度使用jQuery 1. jQuery速度再快,也无法与原生的javascript方法相比,而且建立的jQuery对象包含的信息量很庞大.所以有原生方法可以使用的场 ...

  9. Linux之环境搭建(一)

    四大系统比较 Mac OS是苹果机专用系统,是基于Unix内核的图形化操作系统,因此Unix相当于父亲,Linux和Mac OS是对兄弟. CentOS是从Redhat源代码编译重新发布版.CentO ...

  10. <玩转Django2.0>读书笔记:邮件和分页

    1. 发送邮件 # settings.py设置 # 邮箱设置 EMAIL_USE_SSL = True # 邮件服务器 EMAIL_HOST = 'smtp.qq.com' # 邮件服务端口 EMAI ...