word文檔的導出(用freemarker模板導出)(桃)


1、將要導出的word文檔另存為xml格式的

2、用文檔編輯器打開(如:notepad++),將要展示的數據用${name}的形式替換,“name”對應數據庫中的字段

3、根據模板生成

package com.idcsol.apps.common.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

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

public class DocumentHandler {

private Configuration configuration = null;

public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}

public void createDoc(Map<String,Object> dataMap,String fileName,
String tempName) throws UnsupportedEncodingException {
//dataMap 要填入模本的數據文件
//設置模本裝置方法和路徑,FreeMarker支持多種模板裝載方法。可以重servlet,classpath,數據庫裝載,
//這里我們的模板是放在template包下面
configuration.setClassForTemplateLoading(this.getClass(), "/com/idcsol/apps/controller/positionSet/template");
Template t=null;
try {
//test.ftl為要裝載的模板
t = configuration.getTemplate(tempName);
} catch (IOException e) {
e.printStackTrace();
}
//輸出文檔路徑及名稱
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//這個地方對流的編碼不可或缺,使用main()單獨調用時,應該可以,但是如果是web請求導出時導出后word文檔就會打不開,並且包XML文件錯誤。主要是編碼格式不正確,無法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}

try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

//System.out.println("---------------------------");
}
}

4、控制器中使用

DocumentHandler  mdoc = new DocumentHandler ();

String resourcepath = "文件名.doc";
mdoc.createDoc(dataMap, resourcepath,"remoceApplyOut.ftl");

5、通過上述實現,word文檔已經導出到服務器上,但是,一般會需要把文件下載到客戶機上

實現代碼:

package com.idcsol.apps.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import com.idcsol.base.common.constant.BaseConst;
import com.idcsol.base.common.utils.StringUtil;

public class UploadUtil {

private static Log log = LogFactory.getLog(UploadUtil.class);

/**
* 上傳文件(下載文件的話不需要該方法)
* @param file
* @return 文件在服務器的相對路徑
*/
public static String uploadFile(MultipartFile file) {

String url = "";

String path = "/upload";
try {
// 獲取絕對路徑
String realPath = com.idcsol.apps.common.constant.Const.REAL_PATH + path;

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 設置日期格式
String date = df.format(new Date());

realPath = realPath + "/" + date;

// 創建文件夾
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}

// 構建文件名
String fileName = "" + new Date().getTime();
int ext = 0;
if ((ext = file.getOriginalFilename().lastIndexOf(".")) != -1) {
// 擴展名
fileName += file.getOriginalFilename().substring(ext);
}

path = path + "/" + date + "/" + fileName; // 相對路徑

url = realPath + "/" + fileName;
file.transferTo(new File(url));

} catch (Exception e) {
log.error(StringUtil.getExceptionDetail(e));
return "";
}

return path;

}

public static void downloadFile(String resourcepath,String filename, HttpServletRequest request,
HttpServletResponse response) {
// String[] fileName1=resourcepath.split("/");
// String fileName=fileName1[fileName1.length-1];
FileInputStream fis = null;
OutputStream out = null;
if(StringUtil.isNotEmpty(filename) && StringUtil.isNotEmpty(resourcepath)) {
try {
//fileName = java.net.URLDecoder.decode(fileName,"UTF-8");
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF");
realPath=realPath.replace("\\hrm\\WEB-INF","");
realPath.trim();
fis = new FileInputStream(new File(resourcepath));
//設置響應頭和保存文件名
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=" + filename);
//寫出流信息
int b = BaseConst.ZERO;
out = response.getOutputStream();
byte [] buf = new byte[1024];
while(-1 != (b = fis.read(buf))) {
out.write(buf,0,b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

6、控制器中調用下載的方法

UploadUtil.downloadFile(resourcepath, Docname, request, response);//文件路徑、文件名

7、如果導出的文件在服務器上沒有必要留下來的話,可以將對應文件刪除

public boolean delDoc(HttpServletRequest request ,HttpSession httpSession,
String docName) throws UnsupportedEncodingException {
Result<Object> result = new Result<Object>();
String docname=docName;
// System.out.println(docname+"docname");
String lj= request.getRealPath("/")+docname;
boolean flag = false;
File file = new File(lj);
// 判斷目錄或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判斷是否為文件
/* if (file.isFile()) { // 為文件時調用刪除文件方法
return deleteFile(lj);
}*/ /*else { // 為目錄時調用刪除目錄方法
return deleteDirectory(lj);
} */
deleteFile(lj);
}
return flag;
}
private boolean deleteFile(String lj) {
// TODO Auto-generated method stub
boolean flag = false;
File file = new File(lj);
// 路徑為文件且不為空則進行刪除
if (file.isFile() && file.exists()) {
file.delete();
// System.out.println("刪除成功");
flag = true;
}
return flag;
}

8、控制器中調用刪除文件的方法

delDoc(request,httpSession,Docname);

需要導入freemarker的jar包

maven  pom.xml的寫法

<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.8</version>
</dependency>

(導出word文檔的方法完)

 


免責聲明!

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



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