导出word并且插入图片

java 复制代码
	// 导出报告 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(); // 创建 PictureRenderData

			map.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模板对象,支持导出包含统计图表的报告文档。

如果不插图片就简单了

代码如下

java 复制代码
/**
	 * 传入 对象  返回生成的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;
	}
相关推荐
吃我一窝jio5 小时前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw6 小时前
C++ union 的一种妙用法
开发语言·c++
何以解忧唯有撸码7 小时前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
starzy19908 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
布莱克60510 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
敲上瘾10 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
联犀11 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
lcj251113 小时前
[C++] C++11
开发语言·c++·笔记
Evand J14 小时前
【MATLAB例程】基于IMM-CKF的AOA+测距融合的二维移动目标跟踪定位
开发语言·matlab·目标跟踪
JianZhen✓16 小时前
IM 聊天列表为什么总“消息乱跳“:有序插入、时间轴派生、本地截断、已读回执
开发语言·前端·php