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. C# 7.0特性

    一.out的形参变量无需再提前声明 befor: "; int numericResult; if (int.TryParse(input, out numericResult)) Cons ...

  2. Xshell 连接虚拟机出现 "The remote SSH server rejected X11 forwarding request"

    1. 描述 虚拟机:VirtualBox Linux: centOS7 解决了 centOS7在VirtualBox中装好后的网络连接问题 后,用 Xshell 连接服务器时出现下面情况: 2. ss ...

  3. Python 爬虫-进阶开发之路

    第一篇:爬虫基本原理: HTTP, 爬虫基础 第二篇:环境安装与搭建: 第三篇:网页抓取:urllib,requests,aiohttp , selenium,  appium 第四篇:网页解析:re ...

  4. JAVA 封装的简单运用

    package Code425;class person{ private String name ; String place; String school; String habits; int ...

  5. java:包、继承,访问修饰符

    包 包(package) 用于管理程序中的类,主要用于解决类的同名问题.包可以看出目录. 包的作用 [1] 防止命名冲突. [2] 允许类组成一个单元(模块),便于管理和维护 [3] 更好的保护类.属 ...

  6. 总结fiddle

    fiddler重新发送请求   模拟限速 http://caibaojian.com/fiddler.html fiddler模拟限速的原理 我们可以通过fiddler来模拟限速,因为fiddler本 ...

  7. IntelliJ IDEA配置Maven

  8. MapReduce词频统计

    自定义Mapper实现 import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; impor ...

  9. web.xml 简记

    web.xml (tomcat启动时读取的配置文件) 首页配置 <welcome-file-list>:index.jsp servlet配置(<servlet>和<se ...

  10. iOS开发之常用路径及文件操作方法

    一.常用的路径方法 1.获取AppName.app 目录路径: NSString *path = [[NSBundle mainBundle] bundlePath]; 2.获取Documents目录 ...