1. 程式人生 > >java freemarker 通過ftl模板檔案匯出word檔案發現在有中文地方出現在亂碼,開啟word檔案提示xml錯誤解決辦法

java freemarker 通過ftl模板檔案匯出word檔案發現在有中文地方出現在亂碼,開啟word檔案提示xml錯誤解決辦法

最近開發一個匯出word模板檔案在本機調整一直正常,但是在伺服器下載下來的檔案老提示xml錯誤,仔細檢視發現出錯的word檔案以xml形式打開發現在在報錯位置有亂碼,

剛開始以為是word轉xml是出現亂碼,單獨除錯word轉xml正常,那應該是向ftl檔案中寫入變數後以寫到檔案流中出現亂碼。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


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


/**
 * 匯出word
 * @author wfy
 *
 */
public class FreemarkerUtil
{
private static FreemarkerUtil util;
private static Configuration cfg;

private FreemarkerUtil(){

}

/**
* 獲取單例物件
* @param pname ftl模板檔案所在路徑
* @return
* @throws IOException 
*/
public static FreemarkerUtil getInstance(String pname) throws IOException{
if(util==null){
cfg=new Configuration();
cfg.setDefaultEncoding("UTF-8");


//cfg.setClassForTemplateLoading(FreemarkerUtil.class, pname);
cfg.setDirectoryForTemplateLoading(new File(pname));
util=new FreemarkerUtil();
}
return util;
}


/**
* 獲取模板物件
* @param fname 模板檔名稱
* @return
*/
private Template getTemplate(String fname){
try
{
//return cfg.getTemplate(fname);
return cfg.getTemplate(fname, "UTF-8");

}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}

/**
* 通過標準輸出流輸出模板的結果
* @param map 資料物件
* @param fname 模板檔名
*/
public void sprint(Map<String,Object>map,String fname){
try
{
getTemplate(fname).process(map, new PrintWriter(System.out));
}
catch (TemplateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}


/**
* 基於檔案輸出
* @param map 資料物件 
* @param fname 模板檔名
* @param outpath 輸出檔案路徑
*/
public void fprint(Map<String,Object> map, String fname, String outpath){
try
{
getTemplate(fname).process(map, new PrintWriter(new File(outpath),"UTF-8"));

}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (TemplateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

}





}

解決辦法:是在三處標紅的位置都加上"UTF-8" 之後所有問題解決

 cfg.setDefaultEncoding("UTF-8");
cfg.getTemplate(fname, "UTF-8");
getTemplate(fname).process(map, new PrintWriter(new File(outpath),"UTF-8"));