一、Controller層調用
//導出爲Word
private void exportWord(String infoId,HttpServletRequest request,HttpServletResponse response) throws Exception{
//registerTime對應xml中EL表達式${registerTime}
map.put("registerTime", map.get("registerTime").toString().substring(0, 10));
map.put("payCarDate", map.get("payCarDate").toString().substring(0, 10));
map.put("cancleDate", map.get("cancleDate").toString().substring(0, 10));
map.put("provideMoney", map.get("provideMoney"));
//圖片轉爲byte64直接插入,barimage也對應xml中EL表達式${barimage}
map.put("barimage", BarcodeUtil.generateBarCode128(map.get("applyCode").toString(), "2", "25"));
//也可以是ftl格式
String templateName = "testXML.xml";// 模板名稱
String wordName = "testWord"; // 導出word名稱
CreateWordUtil.CreateFile(request, response, templateName, wordName, map);
}
二、 Maven引用
<!-- freemarker jar -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
<-- poi jar-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
三、工具類 CreateWordUtil.java
package org.jeecgframework.core.util;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.xerces.impl.dv.util.Base64;
import org.jeecgframework.core.util.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class CreateWordUtil {
/**
* 格式化日期
*
* @param date
* @param oldPattern
* @param newPattern
* @return
*/
public static String StringPattern(String date, String oldPattern,
String newPattern) {
if (date == null || oldPattern == null || newPattern == null)
return "";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern); // 實例化模板對象
SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern); // 實例化模板對象
Date d = null;
try {
d = sdf1.parse(date); // 將給定的字符串中的日期提取出來
} catch (Exception e) { // 如果提供的字符串格式有錯誤,則進行異常處理
e.printStackTrace(); // 打印異常信息
}
return sdf2.format(d);
}
/**
* TODO(生成word模板並下載)
*
* @param freemarker
* @param request
* the request
* @param response
* the response
* @param templateName
* 模板名稱
* @param wordName
* 生成word文檔名稱
* @param dataMap
* 數據綁定
*/
public static void CreateFile(HttpServletRequest request,
HttpServletResponse response, String templateName, String wordName,
Map<String, Object> dataMap) throws Exception {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
String name = "temp" + (int) (Math.random() * 100000) + ".xml";
File f = new File(name);
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
t = configuration.getTemplate(templateName);
// 獲取應用的根路徑保存到本地
/*String servletContextRealPath = request.getServletContext().getRealPath("");
File outFile=new File(servletContextRealPath+"/export/TemporaryFile/" + name);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, w);
if (w != null) {
w.close();
}*/
//輸出到頁面
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
ServletOutputStream out = null;
f.setReadOnly();
f.setWritable(false);
try {
// 調用工具類WordGenerator的createDoc方法生成Word文檔
fin = new FileInputStream(f);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 設置瀏覽器以下載的方式處理該文件默認名爲resume.doc
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(wordName.getBytes("gb2312"), "ISO8859-1")
+ ".doc");
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 (w != null) {
w.close();
}
if (fin != null) {
fin.close();
}
if (out != null) {
out.close();
}
if (f != null) {
f.delete(); // 刪除臨時文件
}
}
}
/**
* TODO(生成word並返回文件)
*
* @param freemarker
* @param request
* the request
* @param response
* the response
* @param templateName
* 模板名稱
* @param wordName
* 生成word文檔名稱
* @param dataMap
* 數據綁定
*/
public static File CreateFile(HttpServletRequest request, String templateName, String wordname,
Map<String, Object> dataMap) {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
String wordpath=request.getSession() .getServletContext().getRealPath("")+"\\expWord\\"+ DateUtils.getMillis()+"\\";
File fpath = new File(wordpath);
if (!fpath.exists()) {
fpath.mkdirs();
}
File f = new File(wordpath+wordname+".doc");
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
try {
t = configuration.getTemplate(templateName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取應用的根路徑保存到本地
/*String servletContextRealPath = request.getServletContext().getRealPath("");
File outFile=new File(servletContextRealPath+"/export/TemporaryFile/" + name);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, w);
if (w != null) {
w.close();
}*/
//輸出到頁面
Writer w=null;
try {
w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
fin = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream("b.txt");
byte[] b = new byte[1024];
while((fin.read(b)) != -1){
fos.write(b);
}
w.close();
fin.close();
fos.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
return f;
}
/**
* TODO(生成word並返回文件)
*
* @param freemarker
* @param request
* the request
* @param response
* the response
* @param templateName
* 模板名稱
* @param wordName
* 生成word文檔名稱
* @param dataMap
* 數據綁定
* @param wordpath
* 根據CheckID生成文件夾
*/
public static File CreateFile2(HttpServletRequest request, String templateName, String wordname,Map<String, Object> dataMap,String wordpath) {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
File fpath = new File(wordpath);
if (!fpath.exists()) {
fpath.mkdirs();
}
File f = new File(wordpath+wordname+".doc");
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
try {
t = configuration.getTemplate(templateName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取應用的根路徑保存到本地
/*String servletContextRealPath = request.getServletContext().getRealPath("");
File outFile=new File(servletContextRealPath+"/export/TemporaryFile/" + name);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, w);
if (w != null) {
w.close();
}*/
//輸出到頁面
Writer w=null;
try {
w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
fin = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream("b.txt");
byte[] b = new byte[1024];
while((fin.read(b)) != -1){
fos.write(b);
}
w.close();
fin.close();
fos.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
return f;
}
/**
* 導出word文件 poi
*
* @param request
* @param response
* @param templateName
* @param wordName
* @param dataMap
*/
public static void ExportWordPoi(HttpServletRequest request,
HttpServletResponse response, String templateName, String wordName,
Map<String, String> dataMap, List<Map<String, String>> list) {
// 獲取應用的根路徑
String servletContextRealPath = request.getServletContext()
.getRealPath("");
// 獲取模板文件
File templateFile = new File(servletContextRealPath
+ "/export/template/" + templateName);
ByteArrayOutputStream ostream = null;
try {
FileInputStream in = new FileInputStream(templateFile);
HWPFDocument hwpfDocument = new HWPFDocument(in);
Range range = hwpfDocument.getRange();
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
range.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
// 輸出 word 內容文件流,提供下載
response.reset();
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename="
+ new String(wordName.getBytes("gb2312"), "ISO8859-1")
+ ".doc");
ostream = new ByteArrayOutputStream();
ServletOutputStream servletOS = response.getOutputStream();
hwpfDocument.write(ostream);
servletOS.write(ostream.toByteArray());
servletOS.flush();
servletOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* TODO(獲取圖片的BASE64編碼) .
*
* @param filename
* the filename
* @return String
* @throws IOException
* String 返回值
*/
public static String getImageString(String filename) throws IOException {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(filename);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
throw e;
} finally {
if (in != null) {
in.close();
}
}
return Base64.encode(data);
}
public static void CreateZipFile(HttpServletRequest request,String templateName, String wordName,Map<String, Object> dataMap) throws Exception {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
String name = "temp" + (int) (Math.random() * 100000) + ".xml";
File f = new File(name);
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
t = configuration.getTemplate(templateName);
//輸出到頁面
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
f.setReadOnly();
f.setWritable(false);
String path = request.getSession().getServletContext().getRealPath("/upload/")+"\\cert\\";
File file = new File(path);
if(!file.exists()) {
file.mkdir();
}
File wordfile = new File(path+wordName+".doc");
fin = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(wordfile);
byte[] b = new byte[1024000];
int n;
while ((n = fin.read(b)) != -1) {
outputStream.write(b, 0, n);
}
if (fin!=null) {
fin.close();
}
if(outputStream!=null){
outputStream.close();
}
}
}
{
/**
* 格式化日期
*
* @param date
* @param oldPattern
* @param newPattern
* @return
*/
public static String StringPattern(String date, String oldPattern,
String newPattern) {
if (date == null || oldPattern == null || newPattern == null)
return "";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldPattern); // 實例化模板對象
SimpleDateFormat sdf2 = new SimpleDateFormat(newPattern); // 實例化模板對象
Date d = null;
try {
d = sdf1.parse(date); // 將給定的字符串中的日期提取出來
} catch (Exception e) { // 如果提供的字符串格式有錯誤,則進行異常處理
e.printStackTrace(); // 打印異常信息
}
return sdf2.format(d);
}
/**
* TODO(生成word模板並下載)
*
* @param freemarker
* @param request
* the request
* @param response
* the response
* @param templateName
* 模板名稱
* @param wordName
* 生成word文檔名稱
* @param dataMap
* 數據綁定
*/
public static void CreateFile(HttpServletRequest request,
HttpServletResponse response, String templateName, String wordName,
Map<String, Object> dataMap) throws Exception {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
String name = "temp" + (int) (Math.random() * 100000) + ".xml";
File f = new File(name);
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
t = configuration.getTemplate(templateName);
// 獲取應用的根路徑保存到本地
/*String servletContextRealPath = request.getServletContext().getRealPath("");
File outFile=new File(servletContextRealPath+"/export/TemporaryFile/" + name);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, w);
if (w != null) {
w.close();
}*/
//輸出到頁面
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
ServletOutputStream out = null;
f.setReadOnly();
f.setWritable(false);
try {
// 調用工具類WordGenerator的createDoc方法生成Word文檔
fin = new FileInputStream(f);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 設置瀏覽器以下載的方式處理該文件默認名爲resume.doc
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(wordName.getBytes("gb2312"), "ISO8859-1")
+ ".doc");
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 (w != null) {
w.close();
}
if (fin != null) {
fin.close();
}
if (out != null) {
out.close();
}
if (f != null) {
f.delete(); // 刪除臨時文件
}
}
}
/**
* TODO(生成word並返回文件)
*
* @param freemarker
* @param request
* the request
* @param response
* the response
* @param templateName
* 模板名稱
* @param wordName
* 生成word文檔名稱
* @param dataMap
* 數據綁定
*/
public static File CreateFile(HttpServletRequest request, String templateName, String wordname,
Map<String, Object> dataMap) {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
String wordpath=request.getSession() .getServletContext().getRealPath("")+"\\expWord\\"+ DateUtils.getMillis()+"\\";
File fpath = new File(wordpath);
if (!fpath.exists()) {
fpath.mkdirs();
}
File f = new File(wordpath+wordname+".doc");
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
try {
t = configuration.getTemplate(templateName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取應用的根路徑保存到本地
/*String servletContextRealPath = request.getServletContext().getRealPath("");
File outFile=new File(servletContextRealPath+"/export/TemporaryFile/" + name);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, w);
if (w != null) {
w.close();
}*/
//輸出到頁面
Writer w=null;
try {
w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
fin = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream("b.txt");
byte[] b = new byte[1024];
while((fin.read(b)) != -1){
fos.write(b);
}
w.close();
fin.close();
fos.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
return f;
}
/**
* TODO(生成word並返回文件)
*
* @param freemarker
* @param request
* the request
* @param response
* the response
* @param templateName
* 模板名稱
* @param wordName
* 生成word文檔名稱
* @param dataMap
* 數據綁定
* @param wordpath
* 根據CheckID生成文件夾
*/
public static File CreateFile2(HttpServletRequest request, String templateName, String wordname,Map<String, Object> dataMap,String wordpath) {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
File fpath = new File(wordpath);
if (!fpath.exists()) {
fpath.mkdirs();
}
File f = new File(wordpath+wordname+".doc");
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
try {
t = configuration.getTemplate(templateName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取應用的根路徑保存到本地
/*String servletContextRealPath = request.getServletContext().getRealPath("");
File outFile=new File(servletContextRealPath+"/export/TemporaryFile/" + name);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
t.process(dataMap, w);
if (w != null) {
w.close();
}*/
//輸出到頁面
Writer w=null;
try {
w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
fin = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream("b.txt");
byte[] b = new byte[1024];
while((fin.read(b)) != -1){
fos.write(b);
}
w.close();
fin.close();
fos.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TemplateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
return f;
}
/**
* 導出word文件 poi
*
* @param request
* @param response
* @param templateName
* @param wordName
* @param dataMap
*/
public static void ExportWordPoi(HttpServletRequest request,
HttpServletResponse response, String templateName, String wordName,
Map<String, String> dataMap, List<Map<String, String>> list) {
// 獲取應用的根路徑
String servletContextRealPath = request.getServletContext()
.getRealPath("");
// 獲取模板文件
File templateFile = new File(servletContextRealPath
+ "/export/template/" + templateName);
ByteArrayOutputStream ostream = null;
try {
FileInputStream in = new FileInputStream(templateFile);
HWPFDocument hwpfDocument = new HWPFDocument(in);
Range range = hwpfDocument.getRange();
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
range.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
// 輸出 word 內容文件流,提供下載
response.reset();
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename="
+ new String(wordName.getBytes("gb2312"), "ISO8859-1")
+ ".doc");
ostream = new ByteArrayOutputStream();
ServletOutputStream servletOS = response.getOutputStream();
hwpfDocument.write(ostream);
servletOS.write(ostream.toByteArray());
servletOS.flush();
servletOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* TODO(獲取圖片的BASE64編碼) .
*
* @param filename
* the filename
* @return String
* @throws IOException
* String 返回值
*/
public static String getImageString(String filename) throws IOException {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(filename);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
throw e;
} finally {
if (in != null) {
in.close();
}
}
return Base64.encode(data);
}
public static void CreateZipFile(HttpServletRequest request,String templateName, String wordName,Map<String, Object> dataMap) throws Exception {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
String name = "temp" + (int) (Math.random() * 100000) + ".xml";
File f = new File(name);
// 設置FreeMarker的模版文件位置
configuration.setServletContextForTemplateLoading(request.getSession()
.getServletContext(), "export\\template\\");
Template t = null;
// 要裝載的模板
t = configuration.getTemplate(templateName);
//輸出到頁面
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
InputStream fin = null;
f.setReadOnly();
f.setWritable(false);
String path = request.getSession().getServletContext().getRealPath("/upload/")+"\\cert\\";
File file = new File(path);
if(!file.exists()) {
file.mkdir();
}
File wordfile = new File(path+wordName+".doc");
fin = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(wordfile);
byte[] b = new byte[1024000];
int n;
while ((n = fin.read(b)) != -1) {
outputStream.write(b, 0, n);
}
if (fin!=null) {
fin.close();
}
if(outputStream!=null){
outputStream.close();
}
}
}