最近公司做我的项目,须要导出 word 或者 PDF 文档,PDF 实现文档曾经驾轻就熟了,想钻研搞一下 word 文档。通过调研发现了一个好用的开源我的项目 Poi-tl
http://deepoove.com/poi-tl
poi-tl 是一个基于 Apache POI 的 Word 模板引擎,也是一个收费开源的 Java 类库,你能够十分不便的退出到你的我的项目中,并且领有着让人喜悦的个性
性能很弱小,能够基于模板生成, 写了一个 demo
public class Demo {public static void main(String[] args) throws IOException {InputStream inputStream = Demo.class.getResourceAsStream("/template.docx");
String upgrade = "{\"upgradeStrategy\":0,\"fileDownloadModel\":0,\"downloadUrl\":\"http://downloadurl\",\"userName\":\"admin\",\"password\":\"admin\",\"bucket\":\" test\",\"path\":\"test/test.zip\",\"fileName\":\"test.zip\",\"fileSize\":10000,\"signatureMethod\":0,\"signatureValue\":\"123456asadsasdsa\",\"fileVersion\":1.0,\"upgradeStartTime\":\"2022-10-12 18:00:00\",\"extend\":{\"key1\":\"value2\",\"key2\":\"value2\"},\"timestamp\":\"2022-07-11 16:06:54\"}" ;
JSONObject jsonObject = JSONObject.parseObject(upgrade);
HighlightRenderData code = new HighlightRenderData();
code.setCode(JSONObject.toJSONString(jsonObject, true));
code.setLanguage("javascript");
code.setStyle(HighlightStyle.builder().withShowLine(false).withTheme("vs").build());
List<Goods> goods = new ArrayList<>();
Goods good = new Goods();
good.setCount(4);
good.setName("墙纸");
good.setDesc("书房卧室");
good.setDiscount(1500);
good.setPrice(400);
good.setTax(new Random().nextInt(10) + 20);
good.setTotalPrice(1600);
good.setPicture(Pictures.ofUrl("http://deepoove.com/images/icecream.png")
.size(100, 100).create());
goods.add(good);
goods.add(good);
goods.add(good);
List<Params> paramsList = new ArrayList<>();
Params params1 = new Params();
params1.setProductKey("productKey");
params1.setParamType("String");
params1.setDescText("要发送音讯产品的 ProductKey");
paramsList.add(params1);
Params params2 = new Params();
params2.setProductKey("upgradeStrategy");
params2.setParamType("String");
params2.setDescText("降级策略 (0: 立刻降级 1: 定时降级 2: 勾销降级 3: 仅下载 4: 仅降级)");
paramsList.add(params2);
Params params3 = new Params();
params3.setProductKey("downloadUrl");
params3.setParamType("String");
params3.setDescText(null);
paramsList.add(params3);
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
Configure config = Configure.builder().bind("code", new HighlightRenderPolicy()).bind("goods", policy).bind("paramsList",policy) .useSpringEL()
.build();
XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(new HashMap<String, Object>() {{put("title", "Hi, poi-tl Word 模板引擎");
put("code", code);
put("goods", goods);
put("paramsList",paramsList);
}});
template.writeAndClose(new FileOutputStream("output"+UUID.randomUUID().toString().replace("-","")+".docx"));
}
}
word 模板:
文档十分具体