java 列表数据List通过模板导出excel表和word表
1、maven需要的jar包
<!-- exl導(dǎo)出 --> <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 com.yufei.core.util.excel;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map;import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse;import com.yufei.core.util.Const; import com.yufei.core.util.DateUtil; import com.yufei.core.util.PathUtil; import com.yufei.erp.basis.model.my.MySysDeptPerson;public class ExportZsjh {/*** 導(dǎo)出excel表* 1、response* 2、userinfo session對象* 3、list 填充到excel模板中的數(shù)據(jù)* 4、temp 模板表名(如:zsyjh)* 5、downloadName 下載后文件名稱(如:月度計(jì)劃匯總表_)*/public static Map<String, Object> exportExcel(HttpServletResponse response,MySysDeptPerson userinfo,List<?> list,String temp,String downloadName) throws Exception{Map<String, Object> map = new HashMap<String,Object>();//模板地址String templetPath = PathUtil.getClassResources() + "excel/" + temp + ".xls";// 文件寫入地址String tempOut = Const.ZSYJH_ATTACH_ROOTPATH; //這里采用配置的地址,根據(jù)實(shí)際情況修改File filexls = new File(tempOut);if (!filexls.exists() && !filexls.isDirectory()) {//不存在則創(chuàng)建filexls.mkdirs();}String exportPath = filexls.getPath() + "/" + temp + "_" + DateUtil.getDays() + "_" + userinfo.getRealName() + ".xls";File filetemp=new File(exportPath); if(!filetemp.exists()) { //不存在則創(chuàng)建filetemp.createNewFile(); }// 渲染模板文件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 + DateUtil.getDays() + "_" + userinfo.getRealName() + ".xls";String fileName = new String(name.getBytes("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 BufferedOutputStream(response.getOutputStream());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;}/*** 導(dǎo)出word表* 1、response* 2、userinfo session對象* 3、list 填充到excel模板中的數(shù)據(jù)* 4、temp 模板表名(如:zsyjh)* 5、downloadName 下載后文件名稱(如:月度計(jì)劃匯總表_)*/public static Map<String, Object> exportWord(HttpServletResponse response,MySysDeptPerson userinfo,List<?> list,String temp,String downloadName) throws Exception{Map<String, Object> map = new HashMap<String,Object>();File file = null; InputStream fin = null; ServletOutputStream out = null;String templetPath = PathUtil.getClassResources() + "excel/" ; //word模板存放地址String templateName = temp + ".ftl";// 文件寫入地址String tempOut = Const.ZSYJH_ATTACH_ROOTPATH;File filexls = new File(tempOut);if (!filexls.exists() && !filexls.isDirectory()) {//不存在則創(chuàng)建filexls.mkdirs();}String exportPath = filexls.getPath() + "/" + temp + "_" + DateUtil.getDays() + "_" + userinfo.getRealName() + ".doc"; //導(dǎo)出的word文件存放地址File filetemp=new File(exportPath); if(!filetemp.exists()) { //不存在則創(chuàng)建filetemp.createNewFile(); }// 渲染模板文件Map<String, Object> beanParams = new HashMap<String, Object>();beanParams.put("zsjhList", list);try{String name = downloadName + DateUtil.getDays() + "_" + userinfo.getRealName() + ".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.valueOf(URLEncoder.encode(name, "UTF-8"))));out = response.getOutputStream();byte[] buffer = new byte[512]; // 緩沖區(qū) int bytesToRead = -1; // 通過循環(huán)將讀入的Word文件的內(nèi)容輸出到瀏覽器中 while((bytesToRead = fin.read(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 com.yufei.core.util.excel;import net.sf.jxls.transformer.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;import freemarker.template.Configuration; import freemarker.template.Template;/*** excel文件模板方法導(dǎo)出** @author hedh*/ public class ExportUtils {/*** 渲染模板,然后生成新的excel文件** @param templetPath* excel模板存放地址* @param exportPath* 導(dǎo)出的excel文件存放地址* @param beanParams* 填充到excel模板中的數(shù)據(jù)*/public static void writeExcel(String templetPath, String exportPath, Map<String, Object> beanParams) {try {InputStream is = new FileInputStream(templetPath);// 關(guān)聯(lián)模板XLSTransformer transformer = new XLSTransformer();//這里導(dǎo)出.xls文件,需要導(dǎo)出.xlsx的文件需要換成HSSFWorkbookXSSFWorkbook workBook = (XSSFWorkbook) transformer.transformXLS(is, beanParams);OutputStream os = new FileOutputStream(exportPath);workBook.write(os);is.close();os.flush();os.close();} catch (Exception e) {e.printStackTrace();}}/*** 渲染模板,然后生成新的word文件** @param dataMap* 目標(biāo)數(shù)據(jù)* @param templetPath* word模板存放地址* @param templateName* word模板名稱* @param filePath* 導(dǎo)出的word文件存放地址* @param fileName* 文件名稱*/public static File writeWord(Map dataMap, String templetPath, String templateName, String filePath, String fileName) {try {// 創(chuàng)建配置實(shí)例Configuration configuration = new Configuration();// 設(shè)置編碼configuration.setDefaultEncoding("UTF-8");// ftl模板文件configuration.setDirectoryForTemplateLoading(new File(templetPath));// 獲取模板Template template = configuration.getTemplate(templateName);// 輸出文件File outFile = new File(filePath);// 將模板和數(shù)據(jù)模型合并生成文件Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));// 生成文件template.process(dataMap, out);// 關(guān)閉流out.flush();out.close();return outFile;} catch (Exception e) {e.printStackTrace();return null;}} }4、測試類 (根據(jù)實(shí)際數(shù)據(jù)情況修改)
/*** 導(dǎo)出正式月計(jì)劃*/@RequestMapping(value = "/exportYjh", method = RequestMethod.GET)@ResponseBodypublic Map<String, Object> exportYjh(HttpServletResponse response) throws Exception{Map<String, Object> map = new HashMap<String,Object>();PageData pd = new PageData();//參數(shù)pd = this.getPageData();MySysDeptPerson userinfo = (MySysDeptPerson) pd.getSession("userInfo");// 獲取session的值//獲取正式月計(jì)劃集合List<LjyyxYdjdjhb> list = ljyyxydjdjhbService.selectZsYdjdjhbList(pd);//分組后的數(shù)據(jù)Map<String, List<LjyyxYdjdjhb>> resultMap = new HashMap<String, List<LjyyxYdjdjhb>>();//最后需要的數(shù)據(jù)List<MyLjyyxYdjdjhbExport> exportList = new ArrayList<MyLjyyxYdjdjhbExport>();String temp = "zsyjh"; //模板名稱,最好使用英文 String downloadName = "月度計(jì)劃匯總表_"; //導(dǎo)出文件名稱try{String group = pd.getString("group");//對數(shù)據(jù)進(jìn)行分組if(list != null && list.size() >0){if("bh".equals(group)){resultMap.put("", list);}else {for (LjyyxYdjdjhb ljyyxYdjdjhb : list) {if("jldw".equals(group)){//監(jiān)理單位可以為空if(resultMap.containsKey(null != ljyyxYdjdjhb.getJldwfzr() && ljyyxYdjdjhb.getJldwfzr().length() > 0 ? ljyyxYdjdjhb.getJldwfzr().split(",")[0] : "")){//map中異常批次已存在,將該數(shù)據(jù)存放到同一個key(key存放的是異常批次)的map中resultMap.get(null != ljyyxYdjdjhb.getJldwfzr() && ljyyxYdjdjhb.getJldwfzr().length() > 0 ? ljyyxYdjdjhb.getJldwfzr().split(",")[0] : "").add(ljyyxYdjdjhb);} else{//map中不存在,新建key,用來存放數(shù)據(jù)List<LjyyxYdjdjhb> tmpList = new ArrayList<LjyyxYdjdjhb>();tmpList.add(ljyyxYdjdjhb);resultMap.put(null != ljyyxYdjdjhb.getJldwfzr() && ljyyxYdjdjhb.getJldwfzr().length() > 0 ? ljyyxYdjdjhb.getJldwfzr().split(",")[0] : "", tmpList);}}else if("jsdw".equals(group)){if(resultMap.containsKey(ljyyxYdjdjhb.getJsdwmc())){//map中異常批次已存在,將該數(shù)據(jù)存放到同一個key(key存放的是異常批次)的map中resultMap.get(ljyyxYdjdjhb.getJsdwmc()).add(ljyyxYdjdjhb);} else{//map中不存在,新建key,用來存放數(shù)據(jù)List<LjyyxYdjdjhb> tmpList = new ArrayList<LjyyxYdjdjhb>();tmpList.add(ljyyxYdjdjhb);resultMap.put(ljyyxYdjdjhb.getJsdwmc(), tmpList);}}else if("spcs".equals(group)){if(resultMap.containsKey(ljyyxYdjdjhb.getSpcsmc())){//map中異常批次已存在,將該數(shù)據(jù)存放到同一個key(key存放的是異常批次)的map中resultMap.get(ljyyxYdjdjhb.getSpcsmc()).add(ljyyxYdjdjhb);} else{//map中不存在,新建key,用來存放數(shù)據(jù)List<LjyyxYdjdjhb> tmpList = new ArrayList<LjyyxYdjdjhb>();tmpList.add(ljyyxYdjdjhb);resultMap.put(ljyyxYdjdjhb.getSpcsmc(), tmpList);}}}}Set<String> keySet = resultMap.keySet(); //Map中的keyfor (String groupName : keySet) {MyLjyyxYdjdjhbExport mye = new MyLjyyxYdjdjhbExport();mye.setName(groupName);if("1".equals(pd.get("searchXdLx"))){mye.setType("月計(jì)劃");}else{mye.setType("增補(bǔ)月計(jì)劃");}mye.setList(resultMap.get(groupName));exportList.add(mye);}}String type = pd.getString("type");if("excel".equals(type)){map = ExportZsjh.exportExcel(response,userinfo,exportList,temp,downloadName);} else {map = ExportZsjh.exportWord(response,userinfo,exportList,temp,downloadName);}} catch(Exception e){logger.error(e.toString(), e);// 記錄到錯誤日志表this.saveErrorLog("月計(jì)劃導(dǎo)出表", "月計(jì)劃導(dǎo)出表", e);map.put("msg", this.getCommonErrorMessage(e)); // 返回提示信息}return map;}5、模板數(shù)據(jù)類 MyLjyyxYdjdjhbExport.java
package com.yufei.erp.business.model.yjhmanagement.ljyyxydjdjhb.my;import java.util.List;import com.yufei.erp.business.model.rjhmanagement.ljyyxrjdjhb.my.MyLjyyxRjdjhb; import com.yufei.erp.business.model.yjhmanagement.ljyyxydjdjhb.LjyyxYdjdjhb; import com.yufei.erp.business.model.zjhmanagement.ljyyxzjdjhb.LjyyxZjdjhb;public class MyLjyyxYdjdjhbExport {private String name;private List<LjyyxYdjdjhb> list; //月計(jì)劃private List<LjyyxZjdjhb> zList; //周計(jì)劃private List<MyLjyyxRjdjhb> rjhList; //日計(jì)劃private String type;public String getName() {return name;}public void setName(String name) {this.name = name;}public List<LjyyxYdjdjhb> getList() {return list;}public void setList(List<LjyyxYdjdjhb> list) {this.list = list;}public String getType() {return type;}public void setType(String type) {this.type = type;}public List<LjyyxZjdjhb> getzList() {return zList;}public void setzList(List<LjyyxZjdjhb> zList) {this.zList = zList;}public List<MyLjyyxRjdjhb> getRjhList() {return rjhList;}public void setRjhList(List<MyLjyyxRjdjhb> rjhList) {this.rjhList = rjhList;}}6、模板
Excel(這里使用到兩層List)
Word(比較復(fù)雜,需要先轉(zhuǎn)換成ftl文件)
(1)建一個word文件,根據(jù)數(shù)據(jù)把字段填入模板中
(2)將word另存為xml
(3)將xml擴(kuò)展名改為ftl
(4)利用在線格式化工具把ftl里面的內(nèi)容格式化一下(轉(zhuǎn)換成的ftl文件內(nèi)容都擠到一坨了,不利于修改)
(5)搜索 w:tr 可以找到行的起點(diǎn)與結(jié)束點(diǎn)(注意第一對w:tr 是表頭,應(yīng)找第二對 w:tr)
(6)用<#list userList as user> </#list>標(biāo)簽將第二對 w:tr 標(biāo)簽包圍起來(userList是集合的key, user是集合中的每個元素, 類似<c:forEach items=‘userList’ var=‘user’>) (網(wǎng)上教程應(yīng)該很多,不懂的可以百度一下,這里就不多做解釋了)
總結(jié)
以上是生活随笔為你收集整理的java 列表数据List通过模板导出excel表和word表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数论-乘法逆元
- 下一篇: fedora chm 文档 阅读