赞
踩
一、需要模板word文件和document.xml模板配置文件
首先把word文件重命名后缀改为.zip然后打开,就能在word文件夹下就能找到document.xml了
在document.xml模板中需要赋值的地方配置好占位符。
二、导入依赖,编写工具类
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.28</version>
- </dependency>
GenerateWordUtils 工具类(对应路径自己修改)
- package com.example.rabbitmq.util;
-
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.*;
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipFile;
- import java.util.zip.ZipOutputStream;
-
-
- public class GenerateWordUtils {
- private static Logger logger = LoggerFactory.getLogger(GenerateWordUtils.class);
- public static Configuration getConfiguration() throws IOException {
- Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
- //设置编码
- configuration.setDefaultEncoding("utf-8");
- //相对路径
- //configuration.setClassForTemplateLoading(GenerateWordUtils.class, "/templates");//此处设置模板存放文件夹名称
- //绝对路径
- configuration.setDirectoryForTemplateLoading(new File("D:\\S\\CMS\\rabbitmq\\src\\main\\resources\\templates"));//此处设置模板存放文件夹名称
- return configuration;
- }
-
- /**
- * 获取模板字符串输入流
- * @param dataMap 参数,键为绑定变量名,值为变量值
- * @param templateName 模板名称
- * @return
- */
- public static ByteArrayInputStream getFreemarkerContentInputStream(Map dataMap, String templateName) {
- ByteArrayInputStream in = null;
- try {
- Template template = getConfiguration().getTemplate(templateName);
- StringWriter swriter = new StringWriter();
- template.process(dataMap, swriter);
- //这里一定要设置utf-8编码 否则导出的word中中文会是乱码
- in = new ByteArrayInputStream(swriter.toString().getBytes("utf-8"));
- } catch (Exception e) {
- e.printStackTrace();
- logger.error("模板生成错误!");
- }
- return in;
- }
- //outputStream 输出流可以自己定义 浏览器或者文件输出流
- public static void createDocx(Map dataMap, OutputStream outputStream) {
- ZipOutputStream zipout = null;
- String docxPath="D:\\S\\CMS\\rabbitmq\\src\\main\\resources\\templates\\";
- try {
- //内容模板,传值生成新的文件输入流documentInput
- ByteArrayInputStream documentInput = GenerateWordUtils.getFreemarkerContentInputStream(dataMap, "document.xml");//xml模板文件名
- //最初设计的模板,原word文件生成File对象
- File docxFile = new File(docxPath+"demo1.docx");//word文件名称
- System.out.println(docxFile.exists());
- if (!docxFile.exists()) {
- docxFile.createNewFile();
- }
- ZipFile zipFile = new ZipFile(docxFile);//获取原word文件的zip文件对象,相当于解压缩了word文件
- // ZipFile zipFile = new ZipFile(docxPath+"demo1.zip");//获取原word文件的zip文件对象,相当于解压缩了word文件
- System.err.println(zipFile);
- Enumeration< ? extends ZipEntry> zipEntrys = zipFile.entries();//获取压缩文件内部所有内容
- zipout = new ZipOutputStream(outputStream);
- //开始覆盖文档------------------
- int len = -1;
- byte[] buffer = new byte[1024];
- while (zipEntrys.hasMoreElements()) {//遍历zip文件内容
- ZipEntry next = zipEntrys.nextElement();
- InputStream is = zipFile.getInputStream(next);
- if (next.toString().indexOf("media") < 0) {
- zipout.putNextEntry(new ZipEntry(next.getName()));//这步相当于创建了个文件,下面是将流写入这个文件
- if ("word/document.xml".equals(next.getName())) {//如果是word/document.xml由我们输入
- if (documentInput != null) {
- while ((len = documentInput.read(buffer)) != -1) {
- zipout.write(buffer, 0, len);
- }
- documentInput.close();
- }
- } else {
- while ((len = is.read(buffer)) != -1) {
- zipout.write(buffer, 0, len);
- }
- is.close();
- }
- }else{//这里设置图片信息,针对要显示的图片
- zipout.putNextEntry(new ZipEntry(next.getName()));
- while ((len = is.read(buffer)) != -1) {
- zipout.write(buffer, 0, len);
- }
- is.close();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- logger.error("word导出失败:"+e.getStackTrace());
- }finally {
- if(zipout!=null){
- try {
- zipout.close();
- } catch (IOException e) {
- logger.error("io异常");
- }
- }
- if(outputStream!=null){
- try {
- outputStream.close();
- } catch (IOException e) {
- logger.error("io异常");
- }
- }
- }
- }
-
- public static void main(String[] args) throws FileNotFoundException {
- Map map=new HashMap<>();
- map.put("outWarehouseNo","1111");
- map.put("num","20");
- map.put("billLadingNo","20150200133");
- map.put("productName","小类");
- map.put("parentName","(大类)");
- map.put("quantityUnit","方");
- map.put("outQuantityNum","4543.56");
- map.put("clientName","客户1");
- map.put("repertoryName","zhongwen");
- map.put("year","2022");
- map.put("month","08");
- map.put("day","09");
- createDocx(map,new FileOutputStream("D:\\S\\CMS\\rabbitmq\\src\\main\\resources\\templates\\demo.docx"));
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。