温馨提示:如果原来项目中有使用poi一定要避免使用maven时发生冲突,具体参考API文档
Poi-tl Documentation (deepoove.com)http://deepoove.com/poi-tl/#_%E7%89%88%E6%9C%ACmaven准备:
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.0</version>
</dependency>
测试代码:?
package com.demo.testproject.test;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.demo.testproject.entity.User;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
public class Test5 {
public static void main(String[] args) throws Exception{
//数据集合
HashMap<String, Object> dataSource = new HashMap<>();
dataSource.put("title","模板标题");
File file1 = ResourceUtils.getFile("classpath:static/template/template.docx");
List<User> users = new ArrayList<>();
users.add(new User(1,"小明",22,"123456@qq.com"));
users.add(new User(2,"小话",22,"123456@qq.com"));
users.add(new User(3,"小例",22,"123456@qq.com"));
users.add(new User(4,"小刚",22,"123456@qq.com"));
users.add(new User(5,"小物",22,"123456@qq.com"));
users.add(new User(6,"小吗",22,"123456@qq.com"));
users.add(new User(7,"小彭",22,"123456@qq.com"));
users.add(new User(8,"小傲",22,"123456@qq.com"));
// 第0行居中且背景为蓝色的表格
//表头
RowRenderData row0 = Rows.of("序号", "姓名","年龄","邮箱").textColor("FFFFFF").bgColor("4472C4").center().create();
RowRenderData []rowRenderData = new RowRenderData[users.size()+1]; //多增加了一行表头
List<RowRenderData> list = new ArrayList<>();
list.add(row0);
users.forEach(x->{
//将对象的属性遍历到表格中
list.add(Rows.of(String.valueOf(x.getId()),x.getName(),String.valueOf(x.getAge()),x.getEmail()).center().create());
});
//集合转换成数组,需要手动转换,不能使用toArrays方法
for (int i = 0; i < list.size(); i++) {
rowRenderData[i] = list.get(i);
}
Object[] objects = list.toArray();
for (Object obj:objects) {
System.out.println(obj);
}
dataSource.put("table1", Tables.create(rowRenderData));
//输出
XWPFTemplate template = XWPFTemplate.compile(file1).render(dataSource);
try {
Random random = new Random();
int i = random.nextInt(1000);
String outPut = "e:\\"+i+".docx";
System.out.println("输出路径"+outPut);
template.writeAndClose(new FileOutputStream(outPut));
} catch (IOException e) {
e.printStackTrace();
}
}
}
模板存放位置:
?
结果展示?
?
?
优化代码建议:将该类封装成方法传入:模板路径,对象集合,输出模板路径即可,遍历时只需要关注表头和赋值的两行代码即可。
非? ? ?常? ? 好? ?用!
?
|