Java表单提交使用FreeMarker导出word文件

Java使用FreeMarker导出word文件

  • 需求是这样的,提交同时导出word
  • 页面
    导出模板,先把里面的值替换为变量
    导出模板
    准备工作
    将word另存为xml格式
    这里写图片描述

这里写图片描述
将xml中的内容格式化(可以借助插件或者在线格式化)
修改后缀为ftl
修改后长这个样子
这里写图片描述
准备工作完成之后,可以写代码了
点击”保存并导出”

//js代码
function saveAndExport(){
      $("#inputForm").attr("action","${ctx}/fty/builderDiary/saveAndExport");
      $("#inputForm").submit();
}

//.....此处省略.....
<div class="form-actions">
        <shiro:hasPermission name="fty:builderDiary:edit">
            <input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" /> 
            <input class="btn btn-primary" type="button" value="保存并导出" onclick="saveAndExport()"/> 
        </shiro:hasPermission>
        <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)" />
</div>
//.....此处省略.....

跳转到导出的controller中

//java代码
@RequiresPermissions("fty:builderDiary:edit")
    @RequestMapping(value = "saveAndExport")
    public void saveAndExport(BuilderDiary builderDiary,  Model model, RedirectAttributes redirectAttributes,HttpServletResponse response) {
        builderDiaryService.save(builderDiary);
        List<BuilderDiary> diaryList = new ArrayList<BuilderDiary>();
        if(builderDiary.getUnitName()!=null){
            String[] unitNameArr = builderDiary.getUnitName().split (",");
            String[] manageNumArr = builderDiary.getManageNum().split (",");
            String[] workerNumArr = builderDiary.getWorkerNum().split (",");
            String[] mainMissionArr = builderDiary.getMainMission().split (",");
            for(int i=0;i<unitNameArr.length;i++){
                BuilderDiary diary = new BuilderDiary();
                diary.setUnitName(unitNameArr[i]);
                diary.setManageNum(manageNumArr[i]);
                diary.setWorkerNum(workerNumArr[i]);
                diary.setMainMission(mainMissionArr[i]);
                diaryList.add(diary);
            }
        }

        FreeMarkerUtils.exportDoc(response,FreeMarkerUtils.writeTemplate(FreeMarkerUtils.putData(FreeMarkerUtils.BUILDERTITLE,builderDiary.getProjectName(),builderDiary.getSequenceNo(),
                builderDiary.getDate(),builderDiary.getNumber(), builderDiary.getCreateDate(),builderDiary.getWeek(),builderDiary.getWeather(),builderDiary.getTemperature(),builderDiary.getWindPowe(),
                builderDiary.getHumidity(),builderDiary.getProgressComplete(),builderDiary.getProjectActivities(),builderDiary.getSafetySituation(),builderDiary.getFacilityOperations(),
                builderDiary.getOtherActivities(),builderDiary.getExistingProblem(),builderDiary.getSignature(),builderDiary.getCurrentTime(),diaryList
                )));

    }

创建一个工具类FreeMarkerUtils.java

package com.hxrj.modules.sys.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.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.hxrj.common.config.Global;
import com.hxrj.modules.fty.entity.datamanage.BuilderDiary;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtils {

    private static Configuration configuration;
    /**
     * 接待来电记录
     */
    public static final String BUILDERTITLE="builderTitle";

    /**
     * 生成Freemarker配置对象并设置模板读取路径
     */
    static {

        if (null == configuration) {
            configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassForTemplateLoading(FreeMarkerUtils.class, "templates");
            // 设置对象的包装器
            configuration.setObjectWrapper(new DefaultObjectWrapper());
            // 设置异常处理器
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

        }

    }
    /**
     * 生成模板文件
     * @param dataMap
     */
    public static File writeTemplate(Map<String,Object> dataMap){
        Template t = null;
        File outFile = new File(System.currentTimeMillis()+".doc");
        try{
            t = configuration.getTemplate("buildDiary.ftl");  //自定义的ftl文件名
            t.setEncoding("utf-8");
            //File outFile = new File("F:/uploadFile/test.doc");
            //Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); 
            Writer out = new OutputStreamWriter(new FileOutputStream(outFile),"utf-8");
            t.process(dataMap, out);
            out.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return outFile;
    }
    /**
     * 导出word文档
     * @param response
     */
    public static void exportDoc(HttpServletResponse response,File file){
        response.setCharacterEncoding("UTF-8");  
        response.setContentType("application/msword");
        response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());

        InputStream inputStream = null;
        ServletOutputStream out = null;
        try{
             inputStream = new FileInputStream(file);
             out = response.getOutputStream();
             byte[] buffer = new byte[1024];  // 缓冲区  
             int bytesToRead = -1;  
             // 通过循环将读入的Word文件的内容输出到浏览器中  
             while((bytesToRead = inputStream.read(buffer)) != -1) {  
                 out.write(buffer, 0, bytesToRead);  
             }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (inputStream != null) {
                        inputStream.close();
                }
                if (out != null) {
                    out.close();
                }
                if (file != null) {
                    file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 设置模板数据
     * 接收controller中的字段并赋值给map
     */
    public static Map<String,Object> putData(String title,String projectName,String sequenceNo,Date date,String number,Date createDate,String week,
            String weather, String temperature,String windPowe,String humidity,String progressComplete,String projectActivities,
            String safetySituation,String facilityOperations,String otherActivities,String existingProblem,String signature,
            String currentTime,List<BuilderDiary> diaryList){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date currentDate = null;
        try {
            //捕获日期转换异常
            currentDate = sdf.parse(currentTime);
        } catch (ParseException e){
            e.printStackTrace();
        }

        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("title", Global.getConfig(title));
        dataMap.put("projectName",projectName);
        dataMap.put("sequenceNo", sequenceNo);
        dataMap.put("date", date);
        dataMap.put("number", number);
        dataMap.put("createDate", createDate);
        dataMap.put("week", week);
        dataMap.put("weather", weather);
        dataMap.put("temperature", temperature);
        dataMap.put("windPowe",windPowe);
        dataMap.put("humidity", humidity);
        dataMap.put("progressComplete", progressComplete);
        dataMap.put("projectActivities", projectActivities);
        dataMap.put("safetySituation", safetySituation);
        dataMap.put("facilityOperations", facilityOperations);
        dataMap.put("otherActivities", otherActivities);
        dataMap.put("existingProblem", existingProblem);
        dataMap.put("signature", signature);
        dataMap.put("currentTime", currentDate);
        dataMap.put("diaryList", diaryList);
        return dataMap;
    }


}

将ftl文件重命名为 buildDiary.ftl
放在工具类的templates文件夹下
这里写图片描述

阅读更多
换一批

没有更多推荐了,返回首页