java poi word导出

java poi word导出

(含有文字,图像)
导出word效果如下:
在这里插入图片描述思路:建立预期导出word效果,设置为模板,然后填充对应信息,注意,加粗,居中等一些图片,文字格式预先设置好。然后进行文字或者图片填充即可;
1.将word文件另存为xml格式;
2.将文件后缀xml文件打开,修改模板对应填充信息如图下,然后修改后缀名为.ftl
在这里插入图片描述以上模板准备完毕。
3.代码:
入口

@PostMapping(value = "/exportDIY")
    @ResponseBody
    @ApiOperation("多格式导出文件")
    @ControllerLog(description = "多格式导出文件", logLevel = 1)
    public ResponseResult exportDIY(HttpServletResponse response, @RequestBody Map<String, String> request) {
        return logService.exportDIY(response, request);
    }

主题代码:

 try {
                Map<String, Object> datas = new HashMap<String, Object>() {
                    {
                        put("title", "xxxxxxx统计");
                        put("time", getTimeMsg(request));
                        //java图片/base64等格式图片
                        put("image1", URLDecoder.decode(request.get("image1").substring(22), "UTF-8").replaceAll(" ", "+"));
                        put("image2", URLDecoder.decode(request.get("image2").substring(22), "UTF-8").replaceAll(" ", "+"));
                    }
                };
                WordUtils wordUtils = new WordUtils();
                wordUtils.exportMillCertificateWord(response, datas, fileName, "logView.ftl");
            } catch (IOException e) {
                e.printStackTrace();
            }

工具类:

public class WordUtils {

	private static Configuration configuration = null;

	public WordUtils() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		configuration.setClassForTemplateLoading(WordUtils.class, "/templates");
		// 设置异常处理器,这样的话就可以${a.b.c.d}即使没有属性也不会出错
		configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

	}

	public void exportMillCertificateWord(HttpServletResponse response, Map map, String title, String ftlFile)
			throws IOException {
		Template freemarkerTemplate = configuration.getTemplate(ftlFile);
		File file = null;
		InputStream fin = null;
		ServletOutputStream out = null;
		try {
			// 调用工具类的createDoc方法生成Word文档
			file = createDoc(map, freemarkerTemplate);
			fin = new FileInputStream(file);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件名
			String fileName = title + ".doc";
			response.setHeader("Content-Disposition",
					"attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

			out = response.getOutputStream();
			byte[] buffer = new byte[512]; // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while ((bytesToRead = fin.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
		} finally {
			if (fin != null)
				fin.close();
			if (out != null)
				out.close();
			if (file != null && file.exists())
				file.delete(); // 删除临时文件
		}
	}

	public static File createDoc(Map<?, ?> dataMap, Template template) {
		String name = "logView.docx";
		File f = new File(name);
		Template t = template;
		try {
			// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
			Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
			t.process(dataMap, w);
			w.flush();
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
		return f;
	}

}

依赖

   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

依赖不足,自己网上巴拉一哈就妥;
postman自测妥当(图片按照流传入,post请求)
在这里插入图片描述以上!