使用FreeMaker导出excel

来源:互联网 发布:看得见风景的房间 知乎 编辑:程序博客网 时间:2024/05/16 11:01

使用FreeMaker导出excel

  • 使用FreeMaker导出excel
  • 操作步骤
    • 编写excel模板并将excel模板导出为xml
    • 用编辑工具打开xml文件将其修改为 ftl标签用法请自行百度
    • 将文件后缀名改为ftl即可
    • 编写java代码 这样可以不用生成excel文件直接导出下载
    • 异常问题汇总

操作步骤

1.编写excel模板并将excel模板导出为xml


2.用编辑工具打开xml文件将其修改为: ftl标签用法请自行百度

3.将文件后缀名改为ftl即可

4.编写java代码 这样可以不用生成excel文件直接导出下载

public static void exportExcel(HttpServletResponse response,           HttpServletRequest request, Map map, String ftlName) {      String mbFilePath = getPath(request) + "根据自己地址修改";      System.out.println(mbFilePath);      try {           Configuration configuration = new Configuration();           configuration.setDefaultEncoding("utf-8");           configuration.setDirectoryForTemplateLoading(new File(mbFilePath));// 指定ftl所在目录,根据自己的改           String excelName = new String((ftlName + ".xls").getBytes("utf-8"),                     "utf-8");           response.reset(); //此句为防止导出的表格多出其他东西 比如回车等           response.setHeader("Content-Type", "application/x-xls");           response.setHeader("Content-Disposition", "attachment;filename="                     + wordName);           response.setCharacterEncoding("utf-8");// 此句非常关键,不然excel文档全是乱码           PrintWriter out = response.getWriter();           Template t = configuration.getTemplate(ftlName + ".ftl", "utf-8");// 以utf-8的编码读取ftl文件           Map user = getUserInformation(request);           map.put("user", user);           t.process(map, out);           out.flush();           out.close();      } catch (TemplateException e) {           System.out.println("获取excel模板失败");      } catch (IOException e) {           System.out.println("IO错误");      } }

异常问题汇总

数据问题<Data ss:Type="Number">${(data.phone)!" "}</Data></Cell> Type 为Number的情况下是输入的值是字符串造成的报错 比如 <Data ss:Type="Number">出错</Data></Cell>  这样就会出错  ss:ExpandedColumnCount="2"  ss:ExpandedRowCount="2"  值小于列数、行数(解决方案:1.将其值设置很大;2.根据数据行数大小自动增加(后台封装一个数据取即可) 如:ss:ExpandedRowCount="${(total+100)!100}")  ss:index问题:此问题解决方法为index设置较大就可以(多余的没有数据<Row>可以删,不会出错)  4.错误查看方法,因为excel报错文件是受保护的系统文件所以会出现路径无法找到问题(解决方案:打开文件高级设置,去掉隐藏受保护的操作系统文件,将显示隐藏文件打开即可)