java列表数据List通过模板导出excel表和word表
1、maven需要的jar包
<!-- exl导出 -->
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
2、⼯具类 ExportZsjh.java
package l;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import util.Const;
import util.DateUtil;
import util.PathUtil;
import MySysDeptPerson;
public class ExportZsjh {
/**
* 导出excel表
* 1、response
* 2、userinfo    session对象
dj dj
* 3、list      填充到excel模板中的数据
* 4、temp  模板表名(如:zsyjh)
* 5、downloadName  下载后⽂件名称(如:⽉度计划汇总表_)
*/
public static Map<String, Object> exportExcel(HttpServletResponse response,MySysDeptPerson userinfo,List<?> list,String temp,String downloadName) t hrows Exception{
Map<String, Object> map = new HashMap<String,Object>();
//模板地址
String templetPath = ClassResources() + "excel/" + temp + ".xls";
// ⽂件写⼊地址
String tempOut = Const.ZSYJH_ATTACH_ROOTPATH;  //这⾥采⽤配置的地址,根据实际情况修改
String exportPath = Path() + "/" + temp + "_" + Days() + "_" + RealName() + ".xls";
File filetemp=new File(exportPath);
if(!ists())  {
//不存在则创建
}
// 渲染模板⽂件
Map<String, Object> beanParams = new HashMap<String, Object>();
beanParams.put("zsjhList", list);
ExportUtils.writeExcel(templetPath, exportPath, beanParams);
BufferedInputStream in = null;
BufferedOutputStream out = null;
try{
String name = downloadName + Days() + "_" + RealName() + ".xls";
String fileName = new Bytes("UTF-8"), "ISO8859-1");
response.setContentType("application/x-excel");
// response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "inline; filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(filetemp.length()));
in = new BufferedInputStream(new FileInputStream(filetemp));
out = new OutputStream());
byte[] data = new byte[1024];
int len = 0;
while (-1 != (len = in.read(data, 0, data.length))) {
out.write(data, 0, len);
}
map.put("msg", "success");
} catch(Exception e){
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
return map;
}
/**
* 导出word表
* 1、response
* 2、userinfo    session对象
* 3、list      填充到excel模板中的数据
* 4、temp  模板表名(如:zsyjh)
* 5、downloadName  下载后⽂件名称(如:⽉度计划汇总表_)
*/
public static Map<String, Object> exportWord(HttpServletResponse response,MySysDeptPerson userinfo,List<?> list,String temp,String downloadName) t hrows Exception{
Map<String, Object> map = new HashMap<String,Object>();
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
String templetPath = ClassResources() + "excel/" ;    //word模板存放地址
String templateName = temp + ".ftl";
// ⽂件写⼊地址
String tempOut = Const.ZSYJH_ATTACH_ROOTPATH;
String exportPath = Path() + "/" + temp + "_" + Days() + "_" + RealName() + ".doc"; //导出的word⽂件存放地址  File filetemp=new File(exportPath);
if(!ists())  {
//不存在则创建
}
// 渲染模板⽂件
Map<String, Object> beanParams = new HashMap<String, Object>();
beanParams.put("zsjhList", list);
try{
String name = downloadName + Days() + "_" + RealName() + ".doc";
file = ExportUtils.writeWord(beanParams,templetPath,templateName,exportPath,name);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.de(name, "UTF-8"))));
out = OutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读⼊的Word⽂件的内容输出到浏览器中
while((bytesToRead = ad(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
map.put("msg", "success");
} catch(Exception e){
e.printStackTrace();
} finally {
if(fin != null) fin.close();
if(out != null) out.close();
//if(file != null) file.delete();  // 删除临时⽂件
}
return map;
}
}
3、⼯具类 ExportUtils.java
package l;
import net.ansformer.XLSTransformer;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
/**
* excel⽂件模板⽅法导出
*
* @author hedh
*/
public class ExportUtils {
/**
* 渲染模板,然后⽣成新的excel⽂件
*
* @param templetPath
*            excel模板存放地址
* @param exportPath
*            导出的excel⽂件存放地址
* @param beanParams
*            填充到excel模板中的数据
*/
public static void writeExcel(String templetPath, String exportPath, Map<String, Object> beanParams) {
try {
InputStream is = new FileInputStream(templetPath);
// 关联模板
XLSTransformer transformer = new XLSTransformer();
//这⾥导出.xls⽂件,需要导出.xlsx的⽂件需要换成HSSFWorkbook
XSSFWorkbook workBook = (XSSFWorkbook) ansformXLS(is, beanParams);
OutputStream os = new FileOutputStream(exportPath);
workBook.write(os);
is.close();
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 渲染模板,然后⽣成新的word⽂件
*
* @param dataMap
*            ⽬标数据
* @param templetPath
*            word模板存放地址
*  @param templateName
*    word模板名称
* @param filePath
*            导出的word⽂件存放地址
* @param fileName
*            ⽂件名称
*/
public static File writeWord(Map dataMap, String templetPath, String templateName, String filePath, String fileName) {
try {
// 创建配置实例
Configuration configuration = new Configuration();
// 设置编码
configuration.setDefaultEncoding("UTF-8");
// ftl模板⽂件
configuration.setDirectoryForTemplateLoading(new File(templetPath));
// 获取模板
Template template = Template(templateName);
// 将模板和数据模型合并⽣成⽂件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
// ⽣成⽂件
template.process(dataMap, out);
// 关闭流
out.flush();
out.close();
return outFile;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
4、测试类 (根据实际数据情况修改)
/**
* 导出正式⽉计划
*/
@RequestMapping(value = "/exportYjh", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> exportYjh(HttpServletResponse response) throws Exception{
Map<String, Object> map = new HashMap<String,Object>();
PageData pd = new PageData();
//参数
pd = PageData();
MySysDeptPerson userinfo = (MySysDeptPerson) pd.getSession("userInfo");// 获取session的值
//获取正式⽉计划集合
List<LjyyxYdjdjhb> list = ljyyxydjdjhbService.selectZsYdjdjhbList(pd);
//分组后的数据
Map<String, List<LjyyxYdjdjhb>> resultMap = new HashMap<String, List<LjyyxYdjdjhb>>();
//最后需要的数据
List<MyLjyyxYdjdjhbExport> exportList = new ArrayList<MyLjyyxYdjdjhbExport>();
String temp = "zsyjh";    //模板名称,最好使⽤英⽂
String downloadName = "⽉度计划汇总表_";    //导出⽂件名称
try{
String group = pd.getString("group");
//对数据进⾏分组
if(list != null && list.size() >0){
if("bh".equals(group)){
resultMap.put("", list);
}else {
for (LjyyxYdjdjhb ljyyxYdjdjhb : list) {
if("jldw".equals(group)){
//监理单位可以为空
ainsKey(null != Jldwfzr() && Jldwfzr().length() > 0 ? Jldwfzr().split(",")[0] : "")){//map中异常批次已存在,将该数据存放到同⼀个key(key存放的是异常批次)的map中
<(null != Jldwfzr() && Jldwfzr().length() > 0 ? Jldwfzr().split(",")[0] : "").add(ljyyxYdjdjhb);
} else{//map中不存在,新建key,⽤来存放数据
List<LjyyxYdjdjhb> tmpList = new ArrayList<LjyyxYdjdjhb>();
tmpList.add(ljyyxYdjdjhb);
resultMap.put(null != Jldwfzr() && Jldwfzr().length() > 0 ? Jldwfzr().split(",")[0] : "", tmpList);
}
}else if("jsdw".equals(group)){
Jsdwmc())){//map中异常批次已存在,将该数据存放到同⼀个key(key存放的是异常批次)的map中
<(Jsdwmc()).add(ljyyxYdjdjhb);
} else{//map中不存在,新建key,⽤来存放数据
List<LjyyxYdjdjhb> tmpList = new ArrayList<LjyyxYdjdjhb>();
tmpList.add(ljyyxYdjdjhb);
resultMap.Jsdwmc(), tmpList);