導出word並遍歷數據和圖片

一.條件:可根據我的狀況更改與下面部分代碼結合.
1.建一個test.docx文檔.
內容:
clipboard.png數據庫

另保存爲test.xml.重命名爲test.ftl.把test.ftl放入項目指定位置.並修改test.ftl.後端

clipboard.png

clipboard.png

clipboard.png

二.後端實現代碼(測試用):app

1.word操做工具類.工具

public class WordUtil {
private static Logger log = Logger.getLogger(WordUtil.class);
/**
 * @Desc:生成word文件
 * @paramdataMap word中須要展現的動態數據,用map集合來保存
 * @paramtemplateName word模板名稱,例如:test.ftl
 * @paramfilePath文件生成的目標路徑,例如:C:/
 * @paramfileName生成的文件名稱,例如:test.doc
 * */
public static void createWord(Map<String, Object>dataMap,String templateName,String filePath,String fileName){
    try {
//建立配置實例
        Configuration configuration = new Configuration();
//設置編碼
        configuration.setDefaultEncoding("UTF-8");
//ftl模板文件
       /* File file = new File(filePath);
        configuration.setDirectoryForTemplateLoading(file);*/
        configuration.setClassForTemplateLoading(WordUtil.class,"/templates/generator/");//ftl固定存儲位置
//獲取模板
        Template template = configuration.getTemplate(templateName);
//輸出文件
        /*File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();
        String desktopPath = desktopDir.getAbsolutePath();
        File outFile = new File(desktopPath + File.separator + fileName);//輸出到桌面*/
        
        File outFile = new File(filePath + File.separator + fileName);
//若是輸出目標文件夾不存在,則建立
        if (!outFile.getParentFile().exists()){
            outFile.getParentFile().mkdirs();
        }
//將模板和數據模型合併生成文件
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//生成文件
        template.process(dataMap, out);
//關閉流
        out.flush();
        out.close();
    } catch (Exception e) {
        log.error("生成 word文檔(WordUtil)出錯:[msg:"+e.getMessage()+"] ,文件名:" + fileName);
        e.printStackTrace();
    }
}
/** 文件下載
 * @param path 文件路徑全路徑,包含文件名
 * @param response
 * @return
 * */
public static HttpServletResponse downFile(String path, HttpServletResponse response) {
    try {
// path是指欲下載的文件的路徑。
        File file = new File(path);
// 取得文件名。
        String filename = file.getName();
// 以流的形式下載文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
// 清空response
        response.reset();
// 設置response的Header
        String fileName = URLEncoder.encode(filename,"UTF-8");
        if(fileName.length()>150){ 
            fileName=new String(filename.getBytes("GBK"),"ISO-8859-1"); }
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outs = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outs.write(buffer);
        outs.flush();
        outs.close();
        file.delete();
    }catch (IOException e) {
        log.error("下載文檔(WordUtil)出錯:[msg:"+e.getMessage()+"] "); e.printStackTrace(); }
    return response;
}

}測試

2.控制層編碼

@RequestMapping("downWord")
public void DownWord(HttpServletRequest request, String response) throws IOException {
    List<TrainScore> info = new ArrayList<TrainScore>();
//測試數據,也能夠從數據庫中提取
    for(int i=0;i<3;i++){
        TrainScore ts = new TrainScore();
        ts.setId("12345667"+i);
        ts.setUserId("91345678"+i);
        ts.setTrainId("3456789"+i);
        ts.setScore(90+i);
        ts.setComment("測試"+i);
        info.add(ts);
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("title","用戶考覈表數據");
    params.put("info",info);
 //個人圖片位置images/timg.png
    params.put("image",getImageBase("images/timg.png",request));
    params.put("attention","請注意確保全部信息的正確性");
    WordUtil wordUtil = new WordUtil();
    wordUtil.createWord(params,"test.ftl","C:/","test.doc");

}

//得到圖片路徑和base64編碼
private String  getImageBase(String src,HttpServletRequest request) {
    if(src==null||src==""){
        return "";
    }
 //圖片在項目中的路徑
    File file = new File(request.getSession().getServletContext().getRealPath("/")+src.replace(request.getSession().getServletContext().getContextPath(),""));
    if(!file.exists()) {
        return "";
    }
    InputStream in = null;
    byte[] data = null;
    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    try {
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
//加密
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);
}

三.運行結果:加密

clipboard.png

相關文章
相關標籤/搜索