博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据导出生成word附件使用POI的XWPFTemplate对象
阅读量:4307 次
发布时间:2019-06-06

本文共 4164 字,大约阅读时间需要 13 分钟。

比较常用的实现Java导入、导出Excel的技术有两种Jakarta POI和Java Excel。

Jakarta POI 是一套用于访问微软格式文档的Java API。Jakarta POI有很多组件组成,其中有用于

操作Excel格式文件的HSSF和

用于操作Word的HWPF;

 

 

一、前端使用get请求和post请求都可以

get请求:

window.location.href= appPath+"/export/handoverForm?ticketId="+self.ticketId +                    "&complainId="+row.id+"&formCode="+self.exportFormCode.complainDetail;

隐藏form表单改写成post请求,form表单get和post都可以:

$("#dataRange").val(self.table.pageData.dataRange);            $("#processStatus").val(self.table.pageData.processStatus);            $("#startDate").val(self.table.pageData.startDate);            $("#endDate").val(self.table.pageData.endDate);            $("#multiFildMatch").val(self.table.pageData.multiFildMatch);            $('#exportForm').submit();

二、java代码

@ResponseBody    @RequestMapping("/exportWord")    public void exportHandoverForm(HttpServletRequest request,                                   HttpServletResponse response, ExportParam exportParam) {        String projectPath = getProjectPath(request);        String templateFile = getTemplateFile(exportParam, projectPath, request);        Map
data = new HashMap<>(); File file = null; InputStream in = null; ServletOutputStream out = null; try { // 数据源 HandoverModel handoverModel = getHandoverFormData(exportParam.getComplainId()); // 反射机制,获取所有属性对象,在拿到属性值,设置数据 for (Field field : HandoverModel.class.getDeclaredFields()) { // 暴力反射,不是public修饰的属性也要获取 field.setAccessible(true); data.put(field.getName(), field.get(handoverModel)); } // 数据源组成map键值对形式 data.put("reportorList", handoverModel.getReportorList().getDatas()); String fileName = handoverModel.getCaseCode(); String exportFilePath = projectPath + ExportConstant.DEFAULT_EXPORT_PATH; logger.info("----------templateFile:" + templateFile); logger.info("-----------projectPath:" + projectPath); // Configure对象是处理表格数据,可以自适应生成对应行数数据 Configure config = Configure.newBuilder().customPolicy("reportorList", new FileTablePolicy()).build(); // XWPFTemplate对象是处理word文档对象,根据map数据源的键值对渲染文档数据 XWPFTemplate template = XWPFTemplate.compile(templateFile, config).render(data); // 文件生成到本地,先生成好文档,再读取到内存中响应给前台 String downloadFileName = fileName + ".docx"; File outPutFile = new File(exportFilePath); if (!outPutFile.exists()) { outPutFile.mkdirs(); } FileOutputStream outFile = new FileOutputStream(exportFilePath + downloadFileName); template.write(outFile); outFile.flush(); outFile.close(); template.close(); // 通过文件流读取到文件,再将文件通过response的输出流,返回给页面下载 file = new File(projectPath + ExportConstant.DEFAULT_EXPORT_PATH + downloadFileName); in = new FileInputStream(file); response.setCharacterEncoding("utf-8"); response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment;filename=" .concat(String.valueOf(URLEncoder.encode(downloadFileName, "UTF-8")))); out = response.getOutputStream(); byte[] buffer = new byte[512]; int bytesToRead = -1; // 用响应对象response中的输出流读取生成好的文件 while ((bytesToRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } } catch (Exception e) { logger.error("导出word出错", e); } finally { if (in != null) try { in.close(); if (out != null) out.close(); if (file != null) file.delete(); // 删除临时文件 } catch (IOException e) { logger.error("删除删除临时文件出错", e); } } }

使用XWPFTemplate引擎,插件化Configure插入表格;

 三、不需要插入表格:

 

 

XWPFTemplate template = XWPFTemplate.compile(templateFile).render(data);

 

转载于:https://www.cnblogs.com/wmqiang/p/11602884.html

你可能感兴趣的文章
Git基础(三)--常见错误及解决方案
查看>>
Git(四) - 分支管理
查看>>
PHP Curl发送数据
查看>>
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
PHP 实现笛卡尔积
查看>>
Laravel中的$loop
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel 操作redis的各种数据类型
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
laravel 定时任务秒级执行
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>