velocity 導出excel模板

pom:java

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

 

 

java:
 spring

/**
     * 說明:下載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();
    }

 

 

結構:
app

相關文章
相關標籤/搜索