导出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;
	}
相关推荐
武当豆豆17 分钟前
C++编程学习阶段性总结
开发语言·c++
学不动CV了1 小时前
C语言32个关键字
c语言·开发语言·arm开发·单片机·算法
wangnaisheng1 小时前
【C#】GraphicsPath的用法
c#·gdi
你怎么知道我是队长1 小时前
python-enumrate函数
开发语言·chrome·python
小屁孩大帅-杨一凡1 小时前
如何解决ThreadLocal内存泄漏问题?
java·开发语言·jvm·算法
大熋2 小时前
Playwright Python 教程:网页自动化
开发语言·python·自动化
赟赟、嵌入式2 小时前
imx6ul Qt运行qml报错This plugin does not support createPlatformOpenGLContext!
开发语言·qt
cdg==吃蛋糕2 小时前
selenium 使用方法
开发语言·python
爱掉发的小李3 小时前
前端开发中的输出问题
开发语言·前端·javascript
zyx没烦恼3 小时前
五种IO模型
开发语言·c++