Freemarker 轉 WORD 輸出並下載
1.WordUtils.java
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.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class WordUtils {
//配置資訊,程式碼本身寫的還是很可讀的,就不過多註解了
private static Configuration configuration = null;
//這裡注意的是利用WordUtils的類載入器動態獲得模板檔案的位置
// private static final String templateFolder = WordUtils.class.getClassLoader().getResource("../../").getPath() + "WEB-INF/templetes/";
private static final String templateFolder = "H:/我的專案/lm/lm/web/src/main/webapp/WEB-INF/templates";
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
configuration.setDirectoryForTemplateLoading(new File(templateFolder));
} catch (IOException e) {
e.printStackTrace();
}
}
private WordUtils() {
throw new AssertionError();
}
public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,String title,String ftlFile) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 呼叫工具類的createDoc方法生成Word文件
file = createDoc(map,freemarkerTemplate);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 設定瀏覽器以下載的方式處理該檔名
String fileName = title+DateUtil.formatDateDetailTime(new Date()) + ".doc";
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
byte[] buffer = new byte[512]; // 緩衝區
int bytesToRead = -1;
// 通過迴圈將讀入的Word檔案的內容輸出到瀏覽器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 刪除臨時檔案
}
}
private static File createDoc(Map<?, ?> dataMap, Template template) {
String name = "sellPlan.doc";
File f = new File(name);
Template t = template;
try {
// 這個地方不能使用FileWriter因為需要指定編碼型別否則生成的Word文件會因為有無法識別的編碼而無法開啟
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
}
2.Action (方法呼叫)
@RequestMapping("/exportSellPlan")
public @ResponseBody void exportSellPlan(Long id){
Calendar calendar = Calendar.getInstance();// 取當前日期。
if(id!=null){
SellPlan plan=sellService.getSellPlanInfo(id);
//獲得資料
Map<String, Object> map = new HashMap<String, Object>();
map.put("bYear", plan.getBusinessYear()!=null?plan.getBusinessYear():"");
map.put("lYear", plan.getLiveYear()!=null?plan.getLiveYear():"");
map.put("leader",plan.getLeader()!=null?plan.getLeader():"");
map.put("phone", plan.getPhone()!=null?plan.getPhone():"");
map.put("curYear", calendar.get(Calendar.YEAR)+"");
map.put("image", getImageBase(plan.getPositionImage()));
try {
WordUtils.exportMillCertificateWord(getRequest(),getResponse(),map,"方案","sellPlan.ftl");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.Base64 圖片處理
//獲得圖片的base64碼
@SuppressWarnings("deprecation")
public String getImageBase(String src) {
if(src==null||src==""){
return "";
}
File file = new File(getRequest().getRealPath("/")+src.replace(getRequest().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);
}
4.JavaScript (方法呼叫)
window.location.href="<%=path%>/exportSellPlan?id=" + id;//一定要是GIT請求,呼叫瀏覽器下載方法
5.Maven 相關依賴
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency>
2018.08.31 Chenyb 隨筆筆錄,方便自己使用