java+freemarker+word 生成轉換doc文檔


首先需要導入jar  引入包

maven 引入greemarker模板

<!-- freemarker jar -->
<dependency>
     <groupId>org.freemarker</groupId>
     <artifactId>freemarker</artifactId>
     <version>2.3.20</version>
</dependency>

 

這是java 類型的引用 別弄錯

import freemarker.template.Configuration;
import freemarker.template.Template;

 

下面是java代碼

//用於返回一個臨時模板
public Template getTemplate(String filename) {
//Configuration用於讀取ftl文件 Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); /*以下是兩種指定ftl文件所在目錄路徑的方式, 注意這兩種方式都是 * 指定ftl文件所在目錄的路徑,而不是ftl文件的路徑 */ //指定路徑的第一種方式(根據某個類的相對路徑指定) // configuration.setClassForTemplateLoading(WordExportUtils.class,""); //指定路徑 String templateFolder = WordExportHelper.class.getClassLoader().getResource("../../").getPath() + "bizmodules/templates/generatedoc/"; Template t = null; try { configuration.setDirectoryForTemplateLoading(new File(templateFolder)); //以utf-8的編碼讀取ftl文件 String filePath = ""; String targetPath = ""; String ftlfileName = ""; ftlfileName = UUIDUtil.getUUID() + filename; filePath = templateFolder + filename; targetPath = templateFolder + ftlfileName;
        //這里是將文件復制到臨時模板中 WordExportHelper.fileCopy_channel(filePath, targetPath);
        //設置格式 t
= configuration.getTemplate(ftlfileName, "utf-8");
        //刪除多余的ftl WordExportHelper.deleteFile(targetPath); }
catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return t; }

調用時候

//返回template模板
Template t=inviteBidsManager.getTemplate(ftl);
//要替換的參數 map Map map
=inviteBidsManager.generateDoc(inMap);
HttpServletResponse response = (HttpServletResponse) inMap.get(CommonAttribute.HTTP_RESPONSE);
String fileName ="導出word文檔的名字";
try {
    //下載文件
DocGenerateHelper.generateDocWithDownload(map,t, fileName,response);
} catch (Exception e) {
e.printStackTrace();
}

 

 

下面是WordExportHelper幫助類

package com.csnt.scdp.bizmodules.helper;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.Map;

/**
 * Created by yuany on 2018/3/19.
 */
public class WordExportHelper {
    public static void WordExport(HttpServletResponse response, Map dataMap) throws IOException{

        String eventId=(String) dataMap.get("eventId");

        //Configuration用於讀取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

      /*以下是兩種指定ftl文件所在目錄路徑的方式, 注意這兩種方式都是
       * 指定ftl文件所在目錄的路徑,而不是ftl文件的路徑
       */

        //指定路徑的第一種方式(根據某個類的相對路徑指定)

        //指定路徑
        String templateFolder = WordExportHelper.class.getClassLoader().getResource("../../").getPath() + "templates/";
        configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        // 輸出文檔路徑及名稱
        File outFile = new File(eventId+".doc");

        //以utf-8的編碼讀取ftl文件
        Template t = null;
        t = configuration.getTemplate("IllegalTemplate.ftl","utf-8");
        Writer out = null;
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
        try {
            t.process(dataMap, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        out.close();

        InputStream fin = null;
        ServletOutputStream download = null;
        try {
            fin = new FileInputStream(outFile);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            // 設置瀏覽器以下載的方式處理該文件名
            String FileName = eventId+".doc";
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(FileName, "UTF-8"))));
            download=response.getOutputStream();
//            byte[] buffer = new byte[512];  // 緩沖區
//            int bytesToRead = -1;
//            // 通過循環將讀入的Word文件的內容輸出到瀏覽器中
//            while((bytesToRead = fin.read(buffer)) != -1) {
//                download.write(buffer, 0, bytesToRead);
//            }
            IOUtils.copy(fin, download);
            download.flush();
            fin.close();
        }finally {
            if(fin != null) fin.close();
            if(download != null) download.close();
            if(outFile != null) outFile.delete(); // 刪除臨時文件
        }
    }


    public static String getImageStr(String str) {

        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(str);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }



    public static void fileCopy_channel(String filePath,String targetPath) {
        FileChannel input = null;
        FileChannel output = null;
        try {
            input = new FileInputStream(filePath).getChannel();
            output = new FileOutputStream(targetPath).getChannel();
            output.transferFrom(input, 0, input.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
    }

}

 

DocGenerateHelper類

package com.csnt.scdp.bizmodules.helper;

import com.csnt.scdp.framework.helper.IOHelper;
import com.csnt.scdp.framework.util.UUIDUtil;
import freemarker.template.Template;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by weixiao on 2018/9/6.
 */
public class DocGenerateHelper {


    public static String genDoc(Map outMap, Template t, String clientFileName) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("MMddHHmmss");
        String tempFileName = IOHelper.checkPath(System.getProperty("java.io.tmpdir")) + "docgenerate" + File.separator + df.format(new Date()) + File.separator + clientFileName + ".doc";
        File file = new File(tempFileName);
        File fileParent = file.getParentFile();
        //首先創建父類文件夾
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        file.createNewFile();
        Writer out = null;
        try {
            IOHelper.generateEmptyDic(tempFileName, false);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFileName), "utf-8"), 10240);
            t.process(outMap, out);
        } finally {

            out.flush();
            out.close();
        }
        return tempFileName;
    }

    //通過文件輸入輸出流下載word
    //設置向瀏覽器端傳送的文件格式
    public static void generateDocWithDownload(Map outMap, Template t, String clientFileName,HttpServletResponse response) throws Exception {
        if (clientFileName == null || clientFileName == "") {
            clientFileName = UUIDUtil.getUUID();
        }
        String fileName = genDoc(outMap, t, clientFileName);
        response.reset();

        InputStream fis = null;
        OutputStream toClient = null;
        File outFile = new File(fileName);
        try {
            fis = new BufferedInputStream(new FileInputStream(outFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設置response的Header
            clientFileName = URLEncoder.encode(clientFileName + ".doc", "utf-8");                                  //這里要用URLEncoder轉下才能正確顯示中文名稱
            response.addHeader("Content-Disposition", "attachment;filename=" + clientFileName);
            response.addHeader("Content-Length", "" + outFile.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();

            fis.close();
            toClient.close();
        } finally {
            WordExportHelper.deleteFile(fileName);
            String directory=fileName.substring(0,fileName.lastIndexOf("\\"));
            WordExportHelper.deleteFile(directory);
            if (fis != null) {
                fis.close();
            }
            if (toClient != null) {
                toClient.close();
            }
        }
    }

    //通過文件輸入輸出流下載word
    //設置向瀏覽器端傳送的文件格式
    public static void generateDocDownload(String path,String clientFileName,HttpServletResponse response) throws Exception {
        if (clientFileName == null || clientFileName == "") {
            clientFileName = UUIDUtil.getUUID();
        }
//        String fileName=genDoc(clientFileName);
        response.reset();
        InputStream fis = null;
        OutputStream toClient = null;
        File outFile = new File(path);
        try {
            fis = new BufferedInputStream(new FileInputStream(outFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 設置response的Header
//            clientFileName = URLEncoder.encode(clientFileName + ".doc", "utf-8");                                  //這里要用URLEncoder轉下才能正確顯示中文名稱
            response.addHeader("Content-Disposition", "attachment;filename=" + clientFileName);
            response.addHeader("Content-Length", "" + outFile.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.flush();

            fis.close();
            toClient.close();
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (toClient != null) {
                toClient.close();
            }
        }
    }
    public static String genDoc(String clientFileName) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("MMddHHmmss");
        String tempFileName = IOHelper.checkPath(System.getProperty("java.io.tmpdir")) + "docgenerate" + File.separator + df.format(new Date()) + File.separator + clientFileName + ".doc";
        File file = new File(tempFileName);
        File fileParent = file.getParentFile();
        //首先創建父類文件夾
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        file.createNewFile();
        Writer out = null;
        try {
            IOHelper.generateEmptyDic(tempFileName, false);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFileName), "utf-8"), 10240);

        } finally {

            out.flush();
            out.close();
        }
        return tempFileName;
    }


    public static String generateDocWithDownload_temp(Map outMap, Template t, String clientFileName) throws Exception {
        String fileUrl = "";
        if (clientFileName == null || clientFileName == "") {
            clientFileName = UUIDUtil.getUUID();
        }
        String fileName = genDoc(outMap, t, clientFileName);
        HttpServletResponse response = ServletActionContext.getResponse();
        response.reset();

        InputStream fis = null;
        OutputStream toClient = null;
        File outFile = new File(fileName);
        try {
            fis = new BufferedInputStream(new FileInputStream(outFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設置response的Header
            clientFileName = URLEncoder.encode(clientFileName + ".doc", "utf-8");                                  //這里要用URLEncoder轉下才能正確顯示中文名稱
            response.addHeader("Content-Disposition", "attachment;filename=" + clientFileName);
            response.addHeader("Content-Length", "" + outFile.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            fileUrl = outFile.toString();

            fis.close();
            toClient.close();
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (toClient != null) {
                toClient.close();
            }

        }
        return fileUrl;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM