Java用freemarker導出Word 文檔


1.用Microsoft Office Word打開word原件;

2.把需要動態修改的內容替換成***,如果有圖片,盡量選擇較小的圖片幾十K左右,並調整好位置;

3.另存為,選擇保存類型Word 2003 XML 文檔(*.xml)【這里說一下為什么用Microsoft Office Word打開且要保存為Word 2003XML,本人親測,用WPS找不到Word 2003XML選項,如果保存為Word XML,會有兼容問題,避免出現導出的word文檔不能用Word 2003打開的問題】;

4.用Firstobject free XML editor打開文件,選擇Tools下的Indent【或者按快捷鍵F8】格式化文件內容。左邊是文檔結構,右邊是文檔內容;

5. 將文檔內容中需要動態修改內容的地方,換成freemarker的標識。其實就是Map<String, Object>中key,如${landName};

6.在加入了圖片占位的地方,會看到一片base64編碼后的代碼,把base64替換成${image},也就是Map<String, Object>中key,值必須要處理成base64;

  代碼如:<w:binData w:name="wordml://自定義.png" xml:space="preserve">${image}</w:binData>

  注意:“>${image}<”這尖括號中間不能加任何其他的諸如空格,tab,換行等符號。

  如果需要循環,則使用:<#list maps as map></#list>  maps是Map<String, Object>中key,值為數組,map為自定義;

7. 標識替換完之后,模板就弄完了,另存為.ftl后綴文件即可。注意:一定不要用word打開ftl模板文件,否則xml內容會發生變化,導致前面的工作白做了。

 

導出到本地:

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import freemarker.template.Configuration;
import freemarker.template.Template;
import sun.misc.BASE64Encoder;

public class WordTest {

    // 此目錄路徑 要求 完整的路徑,並且 windows 不能以 /開頭 如 : /c:/xxx/xxx
    static URL      freemarker     = WordTest.class.getClassLoader().getResource("freemarker");
    static String freemarkerPath = freemarker != null ? new File(freemarker.getFile()).getAbsolutePath() : new File("freemarker").getAbsolutePath();

    //去除PDF水印文件
    static URL aspose = WordTest.class.getClassLoader().getResource("freemarker");
    static String asposePath = freemarker != null ? new File(freemarker.getFile()).getAbsolutePath() : new File("freemarker").getAbsolutePath();
    
    public static void main(String[] args) {
        WordTest wordTest = new WordTest();
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日HH時mm分");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy.MM.dd");
        Date date = new Date();
        // 要填充的數據, 注意map的key要和word中${xxx}的xxx一致
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Object> list = new ArrayList<Object>();
        for (int i = 0; i < 10; i++) {
            WordUser word = new WordUser();
            word.setImgEntityId(new Long(i));
            word.setImgEntityName("目標" + i);
            word.setLeftUpLatitude(231.342 + i * 10);
            word.setLeftUpLongitude(234.32425 + i * 10);
            list.add(word);
        }
        dataMap.put("date", sdf.format(date));
        dataMap.put("dateTime", sdf1.format(date));
        dataMap.put("organicName", "國有控股");
        dataMap.put("picCreateTime", sdf1.format(new Date()));
        dataMap.put("picCreateTime2", sdf2.format(new Date()));
        dataMap.put("picCreateTime3", sdf3.format(new Date()));
        dataMap.put("imgTypeName", "E-22戰斗機");
        dataMap.put("imgRootName", "無人機");
        dataMap.put("imgEntity", "飛機、戰斗機、殲-22、隱形戰機");
        dataMap.put("list", list);
        
        dataMap.put("station2", "先空下來");
        dataMap.put("coordinate", "先空下來");
        dataMap.put("thematicWords", "境外低軌偵察衛星");

        dataMap.put("imgStr", wordTest.getImageStr2("http://47.93.82.37:8180/1.png"));
        // dataMap.put("imgStr", wordTest.getImageStr("/Users/macbook/Documents/1.png"));
        try {
            wordTest.exportSimpleWord(dataMap);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportSimpleWord(Map<String, Object> dataMap) throws Exception {
        // Configuration用於讀取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        /*
         * 以下是兩種指定ftl文件所在目錄路徑的方式, 注意這兩種方式都是 指定ftl文件所在目錄的路徑,而不是ftl文件的路徑
         */
        // 指定路徑的第一種方式(根據某個類的相對路徑指定)
        // configuration.setClassForTemplateLoading(this.getClass(),"");

        // 指定路徑的第二種方式,我的路徑是C:/a.ftl
        configuration.setDirectoryForTemplateLoading(new File(freemarkerPath));

        // 創建臨時文件
        // File outFile = File.createTempFile("pattern", ".docx");

        // 輸出文檔路徑及名稱
        File outFile = new File("/Users/macbook/Documents/test1.doc");

        // 以utf-8的編碼讀取模版ftl文件
        Template t = configuration.getTemplate("test4.ftl", "utf-8");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
        t.process(dataMap, out);
        out.close();
        // 刪除臨時文件
        // outFile.delete();

        // word文檔轉換成PDF
        String wordPath = "/Users/macbook/Documents/test1.doc";
        doc2pdf(wordPath);
    }
// 獲取圖片流
    public String getImageStr2(String imgPath) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            URL url = new URL(imgPath);
            byte[] by = new byte[1024];
            // 創建鏈接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(60 * 1000);
            InputStream is = conn.getInputStream();
            // 將內容讀取內存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 關閉流
            is.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

    // word轉PDF
    public void doc2pdf(String wordPath) {
//         if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
//         return;
//         }
        try {
            long old = System.currentTimeMillis();
            File file = new File("/Users/macbook/Documents/test1.pdf"); // 新建一個空白pdf文檔
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(wordPath); // Address是將要被轉化的word文檔
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                                         // EPUB, XPS, SWF 相互轉換
            long now = System.currentTimeMillis();
            System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒"); // 轉化用時
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
    public boolean getLicense() {
        boolean result = false;
        try {
            //InputStream is = WordTest.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml應放在..\WebRoot\WEB-INF\classes路徑下
            InputStream is = new FileInputStream(asposePath+"/license2.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

瀏覽器直接下載(get請求):

@RequestMapping(value="/investigation/exportWord",method = RequestMethod.GET)
    @ResponseBody   
    public void exportWord(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        Long imgPicId = Long.valueOf(request.getParameter("imgPicId"));
        // 要填充的數據, 注意map的key要和word中${xxx}的xxx一致
        Map<String, Object> dataMap = exportSimpleWordService.exportSimpleWord(imgPicId);
        //獲取圖片類型名稱作為文件名
        String imgTypeName = (String) dataMap.get("imgTypeName");
        
        // Configuration用於讀取ftl文件
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");

        // 指定路徑我的路徑是C:/a.ftl
        try {
            configuration.setDirectoryForTemplateLoading(new File(freemarkerPath));// 指定ftl所在目錄,根據自己的改
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String((imgTypeName+"偵查要報.doc").getBytes("GBK"), "iso8859-1") + "\"");
            response.setCharacterEncoding("utf-8");// 此句非常關鍵,不然word文檔全是亂碼
            PrintWriter out = response.getWriter();
            Template t = configuration.getTemplate("investigation.ftl", "utf-8");// 以utf-8的編碼讀取ftl文件
            t.process(dataMap, out);
            out.close();
        }
        catch (Exception e) {
            logger.error("轉換成word文檔業務服務異常!", e);
            result.put("respCode", BaseRspConstants.RSP_CODE_FAILUR);
            result.put("respDesc", BaseRspConstants.RSP_DESC_FAILUR);  
        }

        // return jsonObject;
    }

 


免責聲明!

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



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