-
文本测试
-
@Author: Liziba
-
@Date: 2021/6/24 21:49
*/
public class DocTest {
public static void main(String[] args) throws IOException {
String filePath = “D:poi-tltextTest.docx”;
String targetPath = “D:poi-tltextTestTarget.docx”;
XWPFTemplate template = XWPFTemplate.compile(filePath).render(
new HashMap
{
put(“name”, “测试”);
put(“author”, Texts.of(“Liziba”).color(“000000”).create());
put(“link”, Texts.of(“百度”).link(“https://baidu.com”).create());
put(“anchor”, Texts.of(“anchortxt”).anchor(“appendix1”).create());
}
});
template.writeAndClose(new FileOutputStream(targetPath));
}
}
测试结果
4.2 图片
标签
{{@var}}
数据模型
-
String:图片url或者本地路径。默认使用图片自身尺寸
-
PictureRenderData
测试模板
测试代码
package com.lizba.poi;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
public class PictureTest {
public static void main(String[] args) throws IOException {
String filePath = “D:poi-tlpictureTest.docx”;
String targetPath = “D:poi-tlpictureTest2.docx”;
String picPath = “D:poi-tlpic.jpg”;
XWPFTemplate template = XWPFTemplate.compile(filePath).render(
new HashMap
{
// 方法一、图片路径(原大小)
put(“picture”, picPath);
// 方法二、指定图片大小
put(“picture”, Pictures.ofLocal(picPath).size(420,350).center().create());
// 方法三、图片流
put(“picture”, Pictures.ofStream(new FileInputStream(picPath), PictureType.JPEG)
.size(420,350).create());
// 针对网络图片、SVG图片、Java图片都有处理
}
});
template.writeAndClose(new FileOutputStream(targetPath));
}
}
测试结果
4.3 表格
标签
{{#var}}
数据模型
- TableRenderData
测试模板
测试代码
package com.lizba.poi;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
public class TableTest {
public static void main(String[] args) throws IOExceptio 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 n {
String filePath = “D:poi-tltableTest.docx”;
String targetPath = “D:poi-tltableTest2.docx”;
// 表头
RowRenderData tableHead = Rows.of(“姓名”, “性别”, “地址”, “微信公众号”).center().bgColor(“4472c4”).create();
// 第一行
RowRenderData row1 = Rows.create(“张三”, “男”, “广东深圳”, “liziba_98”);
// 第二行
RowRenderData row2 = Rows.create(“李四”, “男”, “广东深圳”, “liziba_98”);
// 合并第一行和第二行的第二列与第三列
MergeCellRule rule = MergeCellRule.builder().map(MergeCellRule.Grid.of(1, 1), MergeCellRule.Grid.of(2, 1))
.map(MergeCellRule.Grid.of(1, 2), MergeCellRule.Grid.of(2, 2)).build();
XWPFTemplate template = XWPFTemplate.compile(filePath).render(
new HashMap
{
put(“table”, Tables.of(tableHead, row1, row2).mergeRule(rule).center().create());
}
});
template.writeAndClose(new FileOutputStream(targetPath));
}
}



