FreeMarker生成word的代码
用于生成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("")}???判斷字符串是空的時候的處理情況
總結
以上是生活随笔為你收集整理的FreeMarker生成word的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Freemarker中如何遍历List
- 下一篇: 取KindEditor中的textare