1. 程式人生 > >使用freemarker模板引擎生成word文檔的開發步驟

使用freemarker模板引擎生成word文檔的開發步驟

ring 進度 ram ted 彈出 模板引擎 adf XML style

1、準備模板文檔,如果word文檔中有表格,只保留表頭和第一行數據;
2、定義變量,將word文檔中的變量用${var_name}替換;
3、生成xml文件,將替換變量符後的word文檔另存為xml文件;
4、格式化xml文件,使用工具(XmlFormat.exe),自動生成格式化後的xml文件;
5、美化xml文件,${}中的內容僅保留變量名;
6、表格,將表格中的行數據用相應的變量替換,在第一行數據的收尾加標簽:<#list tbl1 as tbl1></#list> ,註意:表格可嵌套循環
7、開發後端代碼,參考《簡單示例》。註意改寫Bo中表格屬性的getter方法,若想使用標簽對數字進行有效數字的控制,那麽toGetMap方法返回的數據就不能為字符串。

private List<RiskReportMonth> tabledata109 = new ArrayList<RiskReportMonth>();
public List<RiskReportMonth> getTabledata109() {
    return tabledata109;
}
publicvoid setTabledata109(RiskReportMonth tabledata109) {
    this.tabledata109.add(tabledata109);
}

簡單示例:

1、頁面展示:點擊查詢,生成WORD,彈出下載框(沒有進度條)
2、對應JS:調用controller中的方法,當沒有數據時給予提示

queryRiskReport:function(){
         var viewSelf = this;
         var year = $(‘#year‘).val();
         var month = $(‘#month‘).val();
         $.ajax({
            type:‘GET‘,
            url:$$ctx + "/riskMonthReport/searchByCondition",//程序生成word
            data:{
                year:$(‘#year‘).val(),
                month:$(
‘#month‘).val(), }, success:function(result){ if(result.data){ //生成word另存為 //window.location.href=$$ctx + "/riskMonthReport/download?outFileName="+result.data.outFileName; window.location.href=$$ctx + "/riskMonthReport/download?outFileName="+result.data.outFileName; }else{ bootbox.alert("<span style=‘font-size:16px;‘>文件未生成.</span>"); } } }); },

3、對應controller:searchByCondition():根據年月旬生成word文檔(存在於程序指定的目錄下), download():生成word文檔另存為,讓用戶自定義文檔下載路徑

  @RequestMapping(value="/searchByCondition")
   @ResponseBody
   public Result searchByCondition(String year, String month){
      String condition = year + month;
      //獲得Bo格式的數據
      RiskReportMonthBo bo = riskMonthReportService.searchByCondition(condition);
        try {
          if(bo != null){
             //獲得Map格式的數據
             Map<String, Object> dataMap = new HashMap<String, Object>();
              dataMap = riskMonthReportService.toGetMap(bo);
              //程序生成文件名(非漢字,易亂碼)
              //String outFileName = bo.getOutFileName() + ".doc";
              String outFileName = bo.getOutFileName() + ".doc";
              //在程序裏生成word
              FreemarkerUtils.createDoc("RiskMonthReport.xml",outFileName,dataMap);
              logger.info("文件名:"+outFileName);
            }
      } catch (Exception e) {
         e.printStackTrace();
      }
        return success(bo);
   }
@RequestMapping("/download")
   public void download(String outFileName, HttpServletRequest req, HttpServletResponse resp){
     
      try {
         String filePath = FreemarkerUtils.wordPath+File.separator + outFileName + ".doc";
         logger.info("文件生成路徑:"+filePath);
         FileUtils.downloadFile(new File(filePath), "風險月度分析報告"+ ".doc", req, resp);
        
      } catch (IOException e) {
         e.printStackTrace();
         try {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "文件未生成");
         } catch (IOException e1) {
            e1.printStackTrace();
         }
      }
   }

4、對應Service:查詢數據,封裝bo及map

public interface TenDaysReportService {
   /**
    * 查詢數據,封裝Bo
    * @param condition
    * @authorwangxy 20150718
    * @return
    */
   FactLoanReportPeriodBo searchByCondition(String condition);
   /**
    * 將BO組裝成Map
    * @param bo
    * @authorwangxy 20150721
    * @return
    */
   public Map<String, Object> toGetMap(FactLoanReportPeriodBo bo);
}

5、對應的業務模型類Bo:封裝業務數據, 註意:改寫表格的get方法

privateint  companycount;   // 公司數
      private BigDecimal contractamt ; //放款金額
      publicint getCompanycount() {
         returncompanycount;
      }
      publicvoid setCompanycount(int companycount) {
         this.companycount = companycount;
      }
      public BigDecimal getContractamt() {
         returncontractamt;
      }
      publicvoid setContractamt(BigDecimal contractamt) {
         this.contractamt = contractamt;
      }
     private List<FactLoanReportPeriod> tabledata1=new ArrayList<FactLoanReportPeriod>();
      public List<FactLoanReportPeriod> getTabledata1() {
         returntabledata1;
      }
      publicvoid setTabledata1(FactLoanReportPeriod tabledata1) {
         this.tabledata1.add(tabledata1);
      }

6、對應的實體類:與數據庫表映射

使用freemarker模板引擎生成word文檔的開發步驟