关于使用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();
}

原文地址:https://www.cnblogs.com/TheKiteRunner/p/8623058.html