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 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 {

	/**
	 * 導出excel表
	 * 1、response
	 * 2、userinfo    session對象
	 * 3、list       填充到excel模板中的數據
	 * 4、temp   模板表名(如:zsyjh)
	 * 5、downloadName   下載後文件名稱(如:月度計劃彙總表_)
	 */
	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;   //這裏採用配置的地址,根據實際情況修改
		File filexls = new File(tempOut);
		if (!filexls.exists() && !filexls.isDirectory()) {
			//不存在則創建
			filexls.mkdirs();
		}
		String exportPath = filexls.getPath() + "/" + temp + "_" + DateUtil.getDays() + "_" + userinfo.getRealName() + ".xls";
		File filetemp=new File(exportPath);  
	    if(!filetemp.exists())  { 
	    	//不存在則創建
	    	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;
	}
	
	/**
	 * 導出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) 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()) {
			//不存在則創建
			filexls.mkdirs();
		}
		String exportPath = filexls.getPath() + "/" + temp + "_" + DateUtil.getDays() + "_" + userinfo.getRealName() + ".doc"; //導出的word文件存放地址
		File filetemp=new File(exportPath);  
	    if(!filetemp.exists())  { 
	    	//不存在則創建
	    	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]; // 緩衝區 
			int bytesToRead = -1; 
			// 通過循環將讀入的Word文件的內容輸出到瀏覽器中 
			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文件模板方法導出
 *
 * @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) 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
	 *            目標數據
	 * @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 = configuration.getTemplate(templateName);

			// 輸出文件
			File outFile = new File(filePath);
			// 將模板和數據模型合併生成文件
			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 = this.getPageData();
		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)){
							//監理單位可以爲空
							if(resultMap.containsKey(null != ljyyxYdjdjhb.getJldwfzr() && ljyyxYdjdjhb.getJldwfzr().length() > 0 ? ljyyxYdjdjhb.getJldwfzr().split(",")[0] : "")){//map中異常批次已存在,將該數據存放到同一個key(key存放的是異常批次)的map中
								resultMap.get(null != ljyyxYdjdjhb.getJldwfzr() && ljyyxYdjdjhb.getJldwfzr().length() > 0 ? ljyyxYdjdjhb.getJldwfzr().split(",")[0] : "").add(ljyyxYdjdjhb);
							} else{//map中不存在,新建key,用來存放數據
								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中異常批次已存在,將該數據存放到同一個key(key存放的是異常批次)的map中
								resultMap.get(ljyyxYdjdjhb.getJsdwmc()).add(ljyyxYdjdjhb);
							} else{//map中不存在,新建key,用來存放數據
								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中異常批次已存在,將該數據存放到同一個key(key存放的是異常批次)的map中
								resultMap.get(ljyyxYdjdjhb.getSpcsmc()).add(ljyyxYdjdjhb);
							} else{//map中不存在,新建key,用來存放數據
								List<LjyyxYdjdjhb> tmpList = new ArrayList<LjyyxYdjdjhb>();
								tmpList.add(ljyyxYdjdjhb);
								resultMap.put(ljyyxYdjdjhb.getSpcsmc(), tmpList);
							}
						}
					}
				}
				Set<String> keySet = resultMap.keySet();   //Map中的key
				for (String groupName  : keySet) {
					MyLjyyxYdjdjhbExport mye = new MyLjyyxYdjdjhbExport();
					mye.setName(groupName);
					if("1".equals(pd.get("searchXdLx"))){
						mye.setType("月計劃");
					}else{
						mye.setType("增補月計劃");
					}
					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("月計劃導出表", "月計劃導出表", e);
			map.put("msg", this.getCommonErrorMessage(e)); // 返回提示信息
		}
		return map;
	}

5、模板數據類 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;   //月計劃
	
	private List<LjyyxZjdjhb> zList;  //周計劃
	
	private List<MyLjyyxRjdjhb> rjhList;  //日計劃
	
	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(比較複雜,需要先轉換成ftl文件)
(1)建一個word文件,根據數據把字段填入模板中在這裏插入圖片描述
(2)將word另存爲xml
(3)將xml擴展名改爲ftl
(4)利用在線格式化工具把ftl裏面的內容格式化一下(轉換成的ftl文件內容都擠到一坨了,不利於修改)
(5)搜索 w:tr 可以找到行的起點與結束點(注意第一對w:tr 是表頭,應找第二對 w:tr)
(6)用<#list userList as user> </#list>標籤將第二對 w:tr 標籤包圍起來(userList是集合的key, user是集合中的每個元素, 類似<c:forEach items=‘userList’ var=‘user’>) (網上教程應該很多,不懂的可以百度一下,這裏就不多做解釋了)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章