天天看点

XLSTransformer+模板 导出 Excel

利用excel模板来导出excel文件, 十分方便

@RequestMapping(value = "/download/vin", method = RequestMethod.GET)
	@ResponseBody
	public ResBody exportExcel(HttpServletRequest request) {
		String path = request.getSession().getServletContext().getRealPath("/download/");
		List<Map<String,Object>> list= (List<Map<String, Object>>) testService.findAllVinData(); 
		// 准备好要导出的数据
		File file=null;
		try {
			file = ResourceUtils.getFile("classpath:/conf/testExcel.xlsx");
			// 模板的位置,classpath这个一定要写
		} catch (FileNotFoundException e) {			
			LOGGER.debug("===>找不到模版文件");
			e.printStackTrace();
		}
		return vnDownload(list,file,path);
	}	
           
public ResBody vnDownload(List<Map<String,Object>> list,File file,String path) {		
		Map<String,Object> beans = new HashMap<String,Object>();  
		beans.put("list",list);
		XLSTransformer transformer = new XLSTransformer();  
	    InputStream in=null;  
	    OutputStream out=null;
		String name ="testExcel" // 文件名自己根据需要设定
		try {  
            in=new BufferedInputStream(new FileInputStream(file));
            out = new FileOutputStream(path+ name);
            Workbook workbook=transformer.transformXLS(in, beans);  
            workbook.write(out);  
            out.flush();  
            return new ResBody(RespCode.CODE_0.getCode(),path+name);
            // 把下载地址返回给前端
        } catch (InvalidFormatException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (in!=null){try {in.close();} catch (IOException e) {}}  
            if (out!=null){try {out.close();} catch (IOException e) {}}  
        } 
	    return new ResBody();
		}
           
XLSTransformer+模板 导出 Excel

excel 模板放在这个文件夹下面,模板样子如下

XLSTransformer+模板 导出 Excel

把对应单元格的表头写好