java生成word-xdocreport

pom  maven 引入

 

<!--  doc start -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.core</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document.docx</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
<version>2.0.6</version>
</dependency>

<!-- doc end -->


java 代码
--------------
 //实现类
public static void createXdocreportRe(HttpServletResponse response) throws IOException {
InputStream inputStream = null;
FileOutputStream outputStream = new FileOutputStream("warning_task.docx");
try {
//读取取resource目录下的模板 
inputStream = WordUtil.class.getClassLoader().getResourceAsStream("summary.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(inputStream, TemplateEngineKind.Freemarker);
//2.设置填充字段、填充类以及是否为list。
FieldsMetadata fieldsMetadata = report.createFieldsMetadata();
IContext context = report.createContext();

// 创建内容-text为模版中对应都变量名称
String content = "&#x3c;p&#x3e;我在这里放了一段富文本&#x3c;/p&#x3e;" +
"&#x3c;p&#x3e;我准备测试富文本的处理&#x3c;/p&#x3e;";
content = HtmlUtils.htmlUnescape(content);
context.put("name", "年终总结大会");
context.put("time", "2021年3月26日");
context.put("place", "线上");
context.put("sponsor", "张三");
context.put("content", content);
// InputStream p1 = new FileInputStream(new File("C:\\Users\\DELL\\img\\1.jpg"));
// //context.put("img", p1);
// InputStream p2 = new FileInputStream(new File("C:\\Users\\DELL\\img\\2.jpeg"));
// //new ByteArrayImageProvider(p1)
User u1=new User("张三", "组织部", "广州天河");
User u2=new User("李四", "宣传部", "北京海淀");
List<User> users = new ArrayList<>();
users.add(u1);
users.add(u2);
context.put("userList", users);
fieldsMetadata.load("userList",User.class,true);
// 生成文件
report.setFieldsMetadata(fieldsMetadata);
report.process(context, outputStream);

inputStream.close();
outputStream.close();
} catch (Exception e) {
log.info("生成纪要文件发生异常:<{}>", e.getMessage());
}
}


--------------
doc 模版


需要注意事项

在doc文档中,使用 Ctrl+F9 生成 域 然后 编辑 域

image

 

如果需要遍历 list

则需要 定义list域

 

image

 

别忘了 结束标签

image

 




posted @ 2025-11-24 15:22  javahepeng  阅读(0)  评论(0)    收藏  举报