XLSTransformer+模板 导出 Excel

本文介绍了一种利用Excel模板批量导出数据的方法。通过Java程序处理后台数据,并将其填充到预设的Excel模板中,最终实现数据的快速导出。文章详细展示了如何设置路径、读取模板文件、填充数据及导出文件的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用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();
		}

这里写图片描述
excel 模板放在这个文件夹下面,模板样子如下
这里写图片描述
把对应单元格的表头写好

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值