使用easypoi进行按模板导出excel格式

1.导出代码实现

public class EasypoiExport{
	public void export(String templatePath, String outputPath, Map<String, String> params){
		// 获取数据列表
		List<Map<String, Object>> data = Mapper.searchData(params);
		// 获取模板
		TemplateExportParams templateExportParams =new TemplateExportParams(templatePath+"/模板.xlsx");
		// 塞入数据
		Map<String,Object> map = new HashMap<>();
		map.put("list",JcxqData);
		String fileName = "结果.xlsx";
		// 生成excel文件
		Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, map);
		try (FileOutputStream fileOut = new FileOutputStream(outputPath+"/"+fileName)) {
		    workbook.write(fileOut);
		} catch (IOException e) {
		    e.printStackTrace();
		}
	}
}

2.将文件返回给浏览器

public class Export {

    public void exportToBrowser(Map<String, String> params,String templatePath, String outputPath,  HttpServletResponse httpServletResponse) throws Exception{

        EasypoiExport.export(TemplatePath,OutPath,params);

        String outFileName = "结果.xlsx";

        //返回给浏览器
        File file = new File(OutPath+"/"+outFileName);
        String encodedFileName = URLEncoder.encode(file.getName(), "UTF-8");
        // Set headers for file download
        httpServletResponse.setContentType("application/octet-stream");
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+ encodedFileName);
        httpServletResponse.setCharacterEncoding("UTF-8");
        // Obtain the output stream
        OutputStream outputStream = httpServletResponse.getOutputStream();
        // Read the file from the file system

        FileInputStream fileInputStream = new FileInputStream(file);
        // Write the file contents to the response output stream
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // Close the input stream and flush/close the output stream
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
    }
}

3.模板设置

在这里插入图片描述
注: easypoi依赖于poi,且需要与poi版本进行对应

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值