velocity 导出excel模板

本文提供了一个使用Java和Velocity模板引擎实现的下载Excel文件的方法。该方法通过POST请求接收参数,从服务中获取数据并将其填充到Excel模板中,最终将生成的Excel文件返回给客户端。

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

pom:

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-velocity</artifactId>
		</dependency>

 

 

java:
 

/**
     * 说明:下载Excel文件
     * 
     * @author 胥攀
     * @time:2016年8月8日
     */
    @RequestMapping(value = "/downLoadExcel", method = RequestMethod.POST)
    public void downLoadExcel(HttpServletRequest request, String complanyName, String sampleId, HttpServletResponse response) throws Exception {

        JSONObject detailReport = (JSONObject) sampleDetailReportService.getDetailReport(sampleId);
        Map<String, String> dataMap = (Map<String, String>) detailReport.get("data");
        Properties p = new Properties();
        p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "/usr/local/black");

        VelocityEngine ve = new VelocityEngine();
        ve.init(p);
        Template template = ve.getTemplate("Down.xml", "utf-8");

        VelocityContext context = new VelocityContext();
        Set<String> dataKeys = dataMap.keySet();

        Map<String, String> reportCache = ReportCache.getReportCache();
        Set<String> cacheKey = reportCache.keySet();

        for (String keyName : cacheKey) {
            if (!dataMap.containsKey(keyName)) {
                context.put(reportCache.get(keyName), "--");
            } else {
                if (dataMap.get(keyName) != null) {
                    context.put(reportCache.get(keyName), dataMap.get(keyName));
                } else {
                    context.put(reportCache.get(keyName), "--");
                }
            }
        }

        String fileName = complanyName + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xls");

        PrintWriter writer = response.getWriter();
        template.merge(context, writer);
        writer.flush();
        writer.close();
    }

 

 

结构:

转载于:https://my.oschina.net/u/2253438/blog/756944

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值