1、使用freemarker时须要的jar包:freemarker-2.3.19.jar。java
2、根据需求作出导出模板sql
作出Excle模板缓存
这个没什么说的,直接按照需求作出Excle模板,以下:(这里建议用Excle,别用WPS。后面转存为XML文件时容易报错)app
在Excle里面,建议加上如上图的${list.aa},list为须要遍历的变量,aa为遍历后VO里面的字段,方便在转存后的XML里面找到
less
修改扩展名为ftl,在ftl里面加上 遍历的标签和变量工具
3、获取须要导出的数据ui
能够由前台传回sql筛选条件,在后台拼接后。进行查询数据。编码
在得到相应的list数据后,放入map
spa
//将资产list放入map @SuppressWarnings("rawtypes") Map dataMap = new HashMap<String, List<Lessee>>(); dataMap.put("size", String.valueOf(size));//size是后面提到的表格的初始行数 dataMap.put("list", list);//list 传入模板的list //编写在Excel里面对应的变量 //模版名称 String templateName = "exlessee.ftl"; //导出文件的名称 String exportWord = application.getRealPath("template") + DateUtil.getDateNow("yyyyMMddHHmmss") + ".xls"; exportWord(templateName, dataMap, exportWord, "xxx.xls");
4、封装的exportWord方法code
/** * 导出的工具方法 */ public void exportWord(String templatePath, Map<String, Object> dataMap, String buildFile, String newName) { try { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); String path = application.getRealPath("template"); configuration.setDirectoryForTemplateLoading(new File(path));//此处是本类Class.getResource()相对于模版文件的相对路径 Template template = null; File outFile = new File(buildFile); Writer writer = null; template = configuration.getTemplate(templatePath); template.setEncoding("utf-8"); writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), Charset.forName("utf-8")));//此处为输 出文档编码 template.process(dataMap, writer); writer.flush(); writer.close(); // return true; //设置response的编码方式 response.setContentType("application/x-msdownload"); //设置附加文件名 response.setHeader("Content-Disposition", "attachment;filename=" + new String(newName.getBytes("gbk"), "iso-8859-1")); //读出文件到i/o流 FileInputStream fis = new FileInputStream(outFile); BufferedInputStream buff = new BufferedInputStream(fis); byte[] b = new byte[1024];//至关于咱们的缓存 long k = 0;//该值用于计算当前实际下载了多少字节 //从response对象中获得输出流,准备下载 OutputStream myout = response.getOutputStream(); //开始循环下载 while (k < outFile.length()) { int j = buff.read(b, 0, 1024); k += j; //将b中的数据写到客户端的内存 myout.write(b, 0, j); } //将写入到客户端的内存的数据,刷新到磁盘 myout.flush(); myout.close(); } catch (Exception e) { e.printStackTrace(); // return false; } }