标签:
用于生成word用的freemarker工具类
package com.ucap.netcheck.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* @Title: FreeMarkerUtil.java
* @Package com.ucap.netcheck.utils
* @Description: FreeMarker工具类
* @author Zuoquan Tu
* @date 2015-4-5 下午6:02:11
* @version V1.0
*/
public class FreeMarkerUtil {
private static Configuration configuration = null;
private static Map<String, Template> allTemplates = null;
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//configuration.setClassForTemplateLoading(FreeMarkerUtil.class,
// "../template");
try {
configuration.setDirectoryForTemplateLoading(
new File(TemplateUtil.reportTemplatePath));
} catch (IOException e1) {
e1.printStackTrace();
}
allTemplates = new HashMap<String, Template>();
try {
allTemplates.put("word",configuration.getTemplate(TemplateUtil.templateFileName));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public FreeMarkerUtil() {
}
public static File createDoc(Map<?, ?> dataMap,String type){
String name = "temp" + (int) (Math.random() * 100000) + ".doc";
File f = new File(name);
Template t = allTemplates.get(type);
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word
//文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f),"utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException();
}
return f;
}
public static String getImageString(String fileName) throws IOException {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(fileName);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null){
in.close();
}
}
Base64Encoder encoder = new Base64Encoder();
return data != null ? encoder.encode(data) : "";
}
}
生成word用的springMVC代码
package com.ucap.netcheck.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ucap.netcheck.entity.User;
import com.ucap.netcheck.service.IReport2WordService;
import com.ucap.netcheck.utils.DateUtil;
import com.ucap.netcheck.utils.FreeMarkerUtil;
/**
* @Title: Report2WordController.java
* @Package com.ucap.netcheck.controller
* @Description: 生成word部分的Controller
* @author Zuoquan Tu
* @date 2015-4-12 上午9:36:43
* @version V1.0
*/
@Controller
@RequestMapping(value = "/reportToWord", method = { RequestMethod.GET,
RequestMethod.POST })
public class Report2WordController {
@Autowired
private IReport2WordService report2WordService;
@RequestMapping(value = "/word")
public String outWord(Model model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8");
// 获取innerUUID,taskId
String siteCode = request.getParameter("innerUUID");
// 获取taskId
Integer taskId = Integer.parseInt(request.getParameter("taskId"));
// 获取用户的userId
User user = (User) request.getSession().getAttribute("user");
// 通过下面的方式获得模板的参数
Map<String, Object> map = report2WordService
.generateWordData(siteCode, taskId, user.getId());
// 获取innerUUID,taskId
//Map<String, Object> map = new HashMap<String, Object>();
//获取innerUUID,taskId
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("taskNum", "测试");
// map.put("tackRunNum", "测试2……rqwrqw");
// String imageStr = new FreeMarkerUtil().getImageString("D:/1.png");
// map.put("imgStr", imageStr);
//
// List<CheckService> newsList = new ArrayList<CheckService>();
// for (int i = 0; i < 10; i++) {
// CheckService checkService = new CheckService();
// checkService.setTaskRunNum(10);
// checkService.setTaskNum(1000);
// newsList.add(checkService);
// }
// map.put("newList", newsList);
this.generateWord(response, map);
return null;
}
private void generateWord(HttpServletResponse response,
Map<String, Object> map) throws FileNotFoundException, IOException {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类WordGenerator的createDoc方法生成Word文档
file = new FreeMarkerUtil().createDoc(map, "word");
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件默认名为下面的文件,按照时间来生成的一个文件名称
String longMsDateStr = DateUtil.getStringLongMsDate();
response.addHeader("Content-Disposition","attachment;filename="+longMsDateStr+".doc");
out = response.getOutputStream();
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null)
fin.close();
if (out != null)
out.close();
if (file != null)
file.delete(); // 删除临时文件
}
}
}
Service代码
package com.ucap.netcheck.service;
import java.util.Map;
/**
* @Title: Report2WordService.java
* @Package com.ucap.netcheck.service
* @Description: 用户生成word的报告的service接口
* @author Zuoquan Tu
* @date 2015-4-12 上午9:43:25
* @version V1.0
*/
public interface IReport2WordService {
/**
* generateWordData(通过这个方法获得生成报告所需的数据)
*
* @Title: generateWordData
* @Description: 通过这个方法获得生成报告所需的数据
* @param @return 返回所需的数据
* @return Map<String,Object> 返回的数据
* @throws
*/
public Map<String, Object> generateWordData(
String siteCode,Integer taskId,String userId);
}
package com.ucap.netcheck.service.impl;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ucap.netcheck.combination.beans.TargetTypeParentToChildBean;
import com.ucap.netcheck.common.GenerateKey;
import com.ucap.netcheck.dao.IReport2WordDao;
import com.ucap.netcheck.entity.CheckService;
import com.ucap.netcheck.entity.MainPageScanFail;
import com.ucap.netcheck.entity.MainPageScanResult;
import com.ucap.netcheck.entity.ProblemInfo;
import com.ucap.netcheck.entity.Site;
import com.ucap.netcheck.service.CheckServiceService;
import com.ucap.netcheck.service.IReport2WordService;
import com.ucap.netcheck.service.ISingleRejectResultService;
import com.ucap.netcheck.service.ISiteService;
import com.ucap.netcheck.service.TargetTypeService;
import com.ucap.netcheck.utils.DateUtil;
/**
* @Title: Report2WordServiceImpl.java
* @Package com.ucap.netcheck.service.impl
* @Description:
* @author
* @date 2015-4-12 上午11:58:09
* @version V1.0
*/
@Service
public class Report2WordServiceImpl implements IReport2WordService {
@Autowired
private ISiteService siteService;
@Autowired
private CheckServiceService checkServiceService;
@Autowired
private IReport2WordDao report2WordDao;
@Autowired
private TargetTypeService targetTypeService;
@Autowired
private ISingleRejectResultService singleRejectResultService;
/**
* generateWordData(通过这个方法获得生成报告所需的数据)
* TODO
*
* @Title: generateWordData
* @Description: 通过这个方法获得生成报告所需的数据
* @param @return 返回所需的数据
* @return Map<String,Object> 返回的数据
* @throws
*/
@Override
public Map<String, Object> generateWordData(
String siteCode,Integer taskId,String userId) {
Map<String, Object> map = new HashMap<String, Object>();
//网站名称,首页网址,报告编号,报告日期
Site site = siteService.findSite(siteCode);
map.put("site", site);
//生成报告编号和报告日期
map.put("reportCode", GenerateKey.generateKeyByDate(6));
map.put("reportDate", DateUtil.getYearMonthAndDay());
//检查方法的数据,获得CheckService的值
CheckService checkService = report2WordDao.findCheckService(userId);
map.put("checkService", checkService);
//设置开通时间的日期
map.put("checkServiceOpenTime", DateUtil.dateToStr(checkService.getOpenTime()));
//设置结束时间的日期
map.put("checkServiceCloseTime", DateUtil.dateToStr(checkService.getCloseTime()));
//问题统计部分的数据
List<TargetTypeParentToChildBean> targetTypeBeanStatistics =
targetTypeService.getTargetTypeByParentId(siteCode, taskId);
map.put("targetTypeBeanStatistics", targetTypeBeanStatistics);
//----------------------------------------------------------------------------------
//单项否决部分的问题
//获取站点无法访问的数据,获取单项否决权的数据
//下面是单项否决部分的代码
MainPageScanResult mainPageScanResult =
singleRejectResultService.queryMainPageScanResultUnique(siteCode,taskId);
map.put("mainPageScanResult", mainPageScanResult);
if (null != mainPageScanResult && mainPageScanResult.getFailNum() >= 0 && mainPageScanResult.getSuccessNum() >= 0) {
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(2);
double rate = mainPageScanResult.getFailNum() / mainPageScanResult.getSuccessNum();
String mainPageFailRateString = format.format(rate);
map.put("mainPageFailRateString", mainPageFailRateString);
} else {
map.put("mainPageFailRateString", "");
}
List<MainPageScanFail> queryMainPageScanFailList = new ArrayList<MainPageScanFail>();
if (null != mainPageScanResult) {
queryMainPageScanFailList = singleRejectResultService.queryMainPageScanFailListById(mainPageScanResult.getId());
}
map.put("queryMainPageScanFailList", queryMainPageScanFailList);
// List<MainPageScanResult> mainPageScanResults =
// singleRejectResultService.queryMainPageScaneResultByCondition(siteCode,taskId);
// map.put("mainPageScanResults", mainPageScanResults);
//获取网站不更新的数据
List<Object[]> MainPageUpdateInfoLists = singleRejectResultService.queryMainPageUpdateResultByCondition(siteCode,taskId);
map.put("MainPageUpdateInfoLists", MainPageUpdateInfoLists);
//获取栏目不更新
List<ProblemInfo> problemInfoUnUpdate = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 4);
map.put("problemInfoUnUpdate", problemInfoUnUpdate);
//严重错误
List<ProblemInfo> problemInfoSeriousError = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 5);
map.put("problemInfoSeriousError", problemInfoSeriousError);
//互动回应差
List<ProblemInfo> problemInfoInterAct = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 6);
map.put("problemInfoInterAct", problemInfoInterAct);
//----------------------------------------------------------------------------------
//网站可用性
//1、首页可用性
List<ProblemInfo> problemInfoIndexUsability = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 8);
map.put("problemInfoIndexUsability", problemInfoIndexUsability);
//
// //连接可用性
// List<ProblemInfo> problemInfoLinkUsability = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 9);
// map.put("problemInfoLinkUsability", problemInfoLinkUsability);
//-----------------------------------------------------------------------------------
//信息更新情况
//首页栏目
List<ProblemInfo> problemInfoIndexColumn = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 11);
map.put("problemInfoIndexColumn", problemInfoIndexColumn);
//基本信息
List<ProblemInfo> queryCheckProblemInfoBaseInfo = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 12);
map.put("queryCheckProblemInfoBaseInfo", queryCheckProblemInfoBaseInfo);
//-----------------------------------------------------------------------------------
//互动回应情况
//政务咨询类栏目
List<ProblemInfo> problemInfoGovAdvisory = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 14);
map.put("problemInfoGovAdvisory", problemInfoGovAdvisory);
//调查集体类栏目
List<ProblemInfo> problemInfoSurvey = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 15);
map.put("problemInfoSurvey", problemInfoSurvey);
//互动访谈类栏目
List<ProblemInfo> problemInfoInterview = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 16);
map.put("problemInfoInterview", problemInfoInterview);
//-----------------------------------------------------------------------------------
//服务使用情况
//办事指南
List<ProblemInfo> problemInfoServiceUsedInfo = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 18);
map.put("problemInfoServiceUsedInfo", problemInfoServiceUsedInfo);
//附件下载
List<ProblemInfo> problemInfoAccessory = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 19);
map.put("problemInfoAccessory", problemInfoAccessory);
//在线系统
List<ProblemInfo> problemInfoOnLineInfo = report2WordDao.queryCheckProblemInfo(taskId, siteCode, 20);
map.put("problemInfoOnLineInfo", problemInfoOnLineInfo);
return map;
}
}
关于错误总结:
1.档值为空的时候会报错,处理方式:类似:${(site.wzmc)?default("")} 判断字符串是空的时候的处理情况
标签:
原文地址:http://blog.csdn.net/tototuzuoquan/article/details/45083055