当前位置: 首页 > news >正文

导出word并且插入图片

	// 导出报告 Word文档(仅导出单个Word文件)@GetMapping("/exportReportWord")@ApiOperationSupport(order = 8)@ApiOperation(value = "导出报告 Word 文档", notes = "正式节点才能导出报告")public void exportReportWord(@RequestParam String yearMonth, HttpServletResponse response) {try {// 5. 生成Word文档并直接输出到响应流String fileName = UUID.randomUUID() + ".docx";response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));try (XWPFTemplate template = getXwpfTemplate(null)) {template.write(response.getOutputStream());}} catch (Exception e) {log.error("导出Word失败", e);try {response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败:" + e.getMessage());} catch (IOException ex) {log.error("设置响应错误信息失败", ex);}}}private XWPFTemplate getXwpfTemplate(CmComplaintVO cmComplaintVO) throws IOException {Map<String, Object> map = new HashMap<>();// 1. 处理文本参数(保持原有逻辑)map.put("work_order_time",Optional.ofNullable(LocalDateTime.now()).map(time -> time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).orElse(null));// 处理图片的核心代码Resource imageResource = new ClassPathResource("templates/statistic_chart.png");try (InputStream imageStream = imageResource.getInputStream()) {// 1. 将输入流转换为 BufferedImage(直接从流转换,避免中间字节数组)BufferedImage bufferedImage = ImageIO.read(imageStream);if (bufferedImage == null) {throw new IOException("无法解析图片流,可能是图片格式不支持");}// 2. 使用 Pictures.ofBufferedImage() 创建图片对象PictureRenderData pictureData = Pictures.ofBufferedImage(bufferedImage, PictureType.PNG).size(712, 500) // 设置图片宽高(像素).create(); // 创建 PictureRenderDatamap.put("image", pictureData); // 绑定到模板占位符 {{image}}} catch (IOException e) {log.error("处理图片失败", e);// 可选:添加默认图片或抛出友好异常throw new RuntimeException("导出Word失败:图片处理异常", e);}// 3. 编译模板(必须绑定图片渲染策略)PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource templateResource = resolver.getResource("classpath:/templates/cm_statistics.docx");Configure config = Configure.builder().bind("image", new PictureRenderPolicy()) // 绑定图片渲染策略.build();XWPFTemplate template = XWPFTemplate.compile(templateResource.getInputStream(), config).render(map);return template;}

本文介绍了导出报告Word文档的实现方法。通过Spring Boot的@GetMapping注解创建"/exportReportWord"接口,使用XWPFTemplate工具生成Word文件并直接输出到响应流。方法包含:(1)设置响应头为Word文档类型;(2)调用getXwpTemplate方法处理模板;(3)异常处理机制。模板处理方法getXwpfTemplate包含:文本参数处理(如格式化当前时间)、图片处理(将PNG图片转为BufferedImage并设置尺寸)以及模板编译(绑定图片渲染策略)。该方法最终返回包含动态数据和图片的Word模板对象,支持导出包含统计图表的报告文档。

如果不插图片就简单了

代码如下

/*** 传入 对象  返回生成的word文档* @param cmComplaintVO* @return* @throws IOException*/private XWPFTemplate getXwpfTemplate(CmComplaintVO cmComplaintVO) throws IOException {Map<String, Object> map = new HashMap<>();// 方式1:直接处理map.put("work_order_time",Optional.ofNullable(LocalDateTime.now()).map(time -> time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).orElse(null));// 导出PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource resource = resolver.getResource("classpath:/templates/cm_statistics.docx");
//		Configure config = Configure.builder().bind("table", new LoopRowTableRenderPolicy()).build();
//		XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream(), config).render(map);XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream()).render(map);return template;}

http://www.dtcms.com/a/273925.html

相关文章:

  • 【C++ 深入解析 C++ 模板中的「依赖类型」】
  • 「Linux命令基础」Shell命令基础
  • PC网站和uniapp安卓APP、H5接入支付宝支付
  • 基于ASP.NET+SQL Server实现(Web)企业进销存管理系统
  • 《探索电脑麦克风声音采集多窗口实时可视化技术》
  • 【Springboot】Bean解释
  • Jenkins 自动触发执行的配置
  • Ntfs!NtfsCheckpointVolume函数中的Ntfs!LfsFlushLfcb函数对Lfcb->LogHeadBuffer进行了赋值--重要
  • 冒泡、选择、插入排序:三大基础排序算法深度解析(C语言实现)
  • 模型训练的常用方法及llama-factory支持的数据训练格式
  • [论文阅读] 人工智能 + 软件工程 | LLM辅助软件开发:需求如何转化为代码?
  • GPT和MBR分区
  • SLICEGPT: COMPRESS LARGE LANGUAGE MODELSBY DELETING ROWS AND COLUMNS
  • 匿名函数作递归函数引用
  • Immutable
  • MetaMask 连接其他网络,连接本地的 Anvil 区块链节点
  • 在Windows非Docker环境安装Redis的几种方法
  • pytest+yaml+allure接口自动化测试框架
  • 在 Postman 中高效生成随机环境变量的完整指南
  • 鸿蒙app 开发中的Record<string,string>的用法和含义
  • 深入探索Kafka Streams:企业级实时数据处理实践指南
  • 关闭 GitLab 升级提示的详细方法
  • AI产品经理面试宝典第8天:核心算法面试题-下
  • 蓝光三维扫描技术在汽车钣金件复杂型面测量中的应用案例
  • 重振索尼复古微型电脑——计划以OrangePi CM5 作为主板升级
  • php 如何通过mysqli操作数据库?
  • springboot生成pdf方案之dot/html/图片转pdf三种方式
  • 【实用IP查询工具】IP数据云-IP地址查询离线库使用方案
  • 【AI大模型】RAG系统组件:向量数据库(ChromaDB)
  • 《数据库》MySQL备份回复