提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
#**
Poi-tl简单应用
**
前言
提示:本文的大概内容:
主要记录了本人在学习简单Poi-tl中遇到的困难及思路
提示:以下是本篇文章正文内容,下面案例可供参考
一、Poi-tl是什么?
个人理解为:可以动态的渲染word文档,可以将数据导出到word档中。
生活实例:将网页中的数据动态的导出到一个word文档中,以便进行数据的统计与对比
二、代码逻辑
1.配置环境
pom配置如下:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.3.0</version>
</dependency>
<!-- Spring Boot Test 依赖 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>3.2.4</version>
<scope>test</scope>
</dependency>
Poi-tl模板引擎
<!-- Poi-tl Word 模板引擎-->
<!-- https://mvnrepository.com/artifact/com.deepoove/poi-tl -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
2.文档操作及渲染
代码如下(示例):
@Test
public void testM(){
//1.获取模板的路径
String s = this.getClass().getClassLoader().getResource("hello2.docx").getPath();
//2.将数据渲染到模板中
XWPFTemplate compile = XWPFTemplate.compile(s);
compile.render(
new HashMap<String, Object>() {{
put("title", "hello");
put("text", "world");
put("author", "aaaaaaa");
put("description", "哈哈哈哈哈哈");
}}
);
try {
//3.此处为输出渲染好的模板
compile.writeAndClose(new FileOutputStream("output4.docx"));
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("test方法调用成功");
运行后输出为经过渲染的文档,下图为两个文档对比:
三、报错及解决办法
在配置的过程中主要遇到了下面的困难
报错1.在配置pom.xml中依赖报错
org.springframework.boot:spring-boot-starter-web:jar:unknown was not found in
http://192.168.1.20:8081/nexus/content/groups/public during a previous attempt.
This failure was cached in the local repository and resolution is not reattempted
until the update interval of nexus-releases has elapsed or updates are forced
解决办法:
经检查,是导入依赖时spring-boot-starter-web和spring-boot-starter-test未写明版本
在网站中查找maven依赖并一键配置,网址如下:
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test/3.2.4
下图是关于查找maven依赖的演示:
报错2.进行测试时报错
java.lang.NullPointerException: Cannot invoke "java.net.URL.getPath()" because the return value
of "java.lang.ClassLoader.getResource(String)" is null
解决办法:
经检查,是导入文档时,导入了不存在的文档,因为项目resources中不存在该文档,所以报错,当把文档名称更改为resources中存在的文档名称时,程序恢复正常
报错3.打开文档后未渲染成功
这个错误其实不算错误,只是本人没有找对文档
解决办法:
本人错以为输出的文档在target文件夹内,其实在外面