Java Web 生成Word文檔(freemarker方式)

首先在pom文件中加入下面這個依賴(不是Maven項目的話,把jar包導入項目便可)

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

1.建立帶有格式的word文檔,將該須要動態展現的數據使用變量符替換。以下:

2.將上述1所建立的文檔另存爲.xml格式。

3.編輯上述2的.xml文件去掉多餘的xml標記,以下圖(紅圈是正確的格式,應該由${變量符}包裹着)

 4.將上述3的文檔另存爲.ftl格式,而後複製到Web項目(下圖目錄)。

 5.JSP頁面提供生成word文檔的按鈕。

<a href="javascript:;" onclick="exportWord('${rightId}')" class="btn btn-success radius"><i class="Hui-iconfont">&#xe644;</i>導出Word</a> 

JS代碼:
//生成word文檔
function exportWord(rightId){
    layer.confirm('確認要生成word文檔嗎?',function(index){
        //關閉窗口
        layer.close(index);
        window.location.href ="<%= basePath%>/biz/SysRight_exportWord.action?rightId="+rightId+""
	});
}

效果以下:

 

6.Action中的exportWord()方法。

/**
	 * 生成word文檔(測試使用)
	 * @Description: TODO
	 * @param @return
	 * @param @throws Exception   
	 * @return String  
	 * @throws
	 * @author uug
	 * @date 2018年12月9日
	 */
	public String exportWord() throws Exception {
        //須要顯示的數據
		sysRight = sysRightService.exportWord(sysRight.getRightId());
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		//建立Map
        Map<String, Object> map = new HashMap<String, Object>();
        //將數據put到Map中,第一個參數爲.ftl文件中對應的${}名稱,第二個參數爲須要顯示的內容
        map.put("rightId",sysRight.getRightId());
        map.put("rightName",sysRight.getRightName());
        map.put("resourcePath",sysRight.getResourcePath());
        map.put("rightPid",sysRight.getRightPid());
        //須要調用的模板名稱
        String downloadType = "test";
        //導出時的名稱
        String fileName = "權限列表";
        WordUtils.exportMillCertificateWord(request,response,map,downloadType , fileName);
		return null;
	}

 6.WordUtils工具類。javascript

@SuppressWarnings("deprecation")
public class WordUtils {
	//配置信息
    private static Configuration configuration = null;
  //這裏注意的是利用WordUtils的類加載器動態得到模板文件的位置
    private static final String templateFolder = WordUtils.class.getClassLoader().getResource("../../").getPath() + "WEB-INF/asserts/templete/";
    //用於存放全部的.ftl文件
    private static Map<String, Template> allTemplates = null;
	
	static {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		allTemplates = new HashMap<String, Template>();
		try {
			configuration.setDirectoryForTemplateLoading(new File(templateFolder));
			//將test.ftl文件存入Map
			allTemplates.put("test", configuration.getTemplate("test.ftl"));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	private WordUtils() {  
        throw new AssertionError();  
    }
 
	/**
	 * 
	 * @Description: TODO
	 * @param @param request
	 * @param @param response
	 * @param @param map 寫入文件的數據
	 * @param @param downloadType  須要調用Map allTemplates對應的那個.ftl文件
	 * @param @param fileName0  設置瀏覽器如下載的方式處理該文件名
	 * @param @throws IOException   
	 * @return void  
	 * @throws
	 * @author uug
	 * @date 2018年12月9日
	 */
    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String downloadType, String fileName0) throws IOException {
        //定義Template對象,注意模板類型名字與downloadType要一致
    	Template template= allTemplates.get(downloadType);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 調用工具類的createDoc方法生成Word文檔
            file = createDoc(map,template);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 設置瀏覽器如下載的方式處理該文件名
            String fileName = fileName0 + ".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(); // 刪除臨時文件
        }
    }
 
    /**
     * 建立doc文檔
     * @Description: TODO
     * @param @param dataMap
     * @param @param template
     * @param @return   
     * @return File  
     * @throws
     * @author uug
     * @date 2018年12月9日
     */
    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = "temp" + (int) (Math.random() * 100000) + ".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;
    }
}

 7.效果以下:java

相關文章
相關標籤/搜索