1. 程式人生 > 程式設計 >基於Freemarker和xml實現Java匯出word

基於Freemarker和xml實現Java匯出word

前言

最近做了一個調查問卷匯出的功能,需求是將維護的題目,答案,匯出成word,參考了幾種方案之後,選擇功能強大的freemarker+固定格式之後的wordxml實現匯出功能。匯出word的程式碼是可以直接複用的,於是在此貼出,並進行總結,方便大家拿走。

實現過程概覽

先在word上,調整好自己想要的樣子。然後存為xml檔案。儲存為freemarker模板,以ftl字尾結尾。將需要替換的變數使用freemarker的語法進行替換。最終將資料準備好,和模板進行渲染,生成檔案並返回給瀏覽器流。

詳細的實現過程準備好word的樣式

我們新建一個word,我們應該使用Microsoft office,如果使用wps可能會造成樣式有些不相容。在新建的office中,設定好我們的表格樣式。我們的調查問卷涉及到四種類型,單選,多選,填空,簡答。我們做出四種類型的示例。

基於Freemarker和xml實現Java匯出word

樣式沒有問題後,我們選擇另存為word xml 2003版本。將會生成一個xml檔案。

基於Freemarker和xml實現Java匯出word

格式化xml,並用freemarker語法替換xml

我們可以先下載一個工具 firstobject xml editor,這個可以幫助我們檢視xml,同時方便我們定位我們需要改的位置。
複製過去之後,按f8可以將其進行格式化,左側是標籤,右側是內容,我們只需要關注w:body即可。

基於Freemarker和xml實現Java匯出word

像右側的調查問卷這個就是個標題,我們實際渲染的時候應該將其進行替換,比如我們的程式資料map中,有title屬性,我們想要這裡展示,我們就使用語法${title}即可。

基於Freemarker和xml實現Java匯出word

freemarker的具體語法,可以參考freemarker的問題,在這裡我給出幾個簡單的例子。

比如我們將所有的資料放置在dataList中,所以我們需要判斷,dataList是不是空,是空,我們不應該進行下面的邏輯,不是空,我們應該先迴圈題目是必須的,答案是需要根據型別進行再次迴圈的。語法參考文件,這裡不再贅述。

程式端引入freemarker

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
</dependency>

將我們的flt檔案放在resources下的templates下。

後端程式碼實現

此程式碼可以複用,在此貼出

public class WordUtils {

  private static Configuration configuration = null;
  private static final String templateFolder = WordUtils.class.getClassLoader().getResource("").getPath()+"/templates/word";
  static {
    configuration = new Configuration();
    configuration.setDefaultEncoding("utf-8");
    try {
      configuration.setDirectoryForTemplateLoading(new File(templateFolder));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * @Description:匯出word,傳入request,response,map就是值,title是匯出問卷名,ftl是你要使用的模板名
   */
  public static void exportWord(HttpServletRequest request,HttpServletResponse response,Map map,String title,String ftlFile) throws Exception {
    Template freemarkerTemplate = configuration.getTemplate(ftlFile);
    File file = null;
    InputStream fin = null;
    ServletOutputStream out = null;
    try {
      file = createDocFile(map,freemarkerTemplate);
      fin = new FileInputStream(file);
      String fileName = title + ".doc";
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
			response.setHeader("Content-Disposition","attachment;filename="
       +fileName);
			out = response.getOutputStream();
      byte[] buffer = new byte[512]; 
      int bytesToRead = -1;
      while((bytesToRead = fin.read(buffer)) != -1) {
        out.write(buffer,bytesToRead);
      }
    }finally {
      if(fin != null) fin.close();
      if(out != null) out.close();
      if(file != null) file.delete(); 
    }
  }

  /**
   * @Description:建立doc檔案
   */
  private static File createDocFile(Map<?,?> dataMap,Template template) {
    File file = new File("init.doc");
    try {
      Writer writer = new OutputStreamWriter(new FileOutputStream(file),"utf-8");
      template.process(dataMap,writer);
      writer.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return file;
  }

}

有了工具類後,我們準備好我們的map資料。map裡面的資料大家可以自行定義。然後呼叫utils中的匯出方法即可。

WordUtils.exportWord(request,response,dataMap,"word","demo.ftl");

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。