//region 数据源 List resultList = new ArrayList(); Model model = new Model(); model.setCode("01"); model.setName("测试1"); resultList.add(model); model = new Model(); model.setCode("02"); model.setName("测试2"); resultList.add(model); //endregion //获得模版 File directory = new File("src/main/resources/templates"); String templatePath = directory.getCanonicalPath(); String templateFile = templatePath + "\\template.xls"; //导出文件名 SimpleDateFormat simpl = new SimpleDateFormat("yyyyMMddHHmmss"); String currntTime = simpl.format(new Date()); String fileName = currntTime + "报表.xls"; //将结果放入 Map beans = new HashMap(); List values = new ArrayList(); values.add(resultList); beans.put("values", values); beans.put("title", "测试title"); //文件名称统一编码格式 fileName = URLEncoder.encode(fileName, "utf-8"); //生成的导出文件 File destFile = File.createTempFile(fileName, ".xls"); //transformer转到Excel XLSTransformer transformer = new XLSTransformer(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //将数据添加到模版中生成新的文件 transformer.transformXLS(templateFile, beans, destFile.getAbsolutePath()); //将文件输入 InputStream inputStream = new FileInputStream(destFile); //设置response参数,可以打开下载页面 response.reset(); //设置响应文本格式 response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); //将文件输出到页面 ServletOutputStream out = response.getOutputStream(); bis = new BufferedInputStream(inputStream); bos = new BufferedOutputStream(out)
2021-05-27 10:50:38 7KB 填充Excel模板 Excel下载
1