实现一个插件就是要告诉我们在模板的某个地方用某些数据做某些事情,我们可以通过实现
RenderPolicy
接口开发自己的插件
模板
1 写一个将标签替换为Hello, world的插件
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.policy.RenderPolicy;
import com.deepoove.poi.template.ElementTemplate;
import com.deepoove.poi.template.run.RunTemplate;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class HelloWorldRenderPolicy implements RenderPolicy {
@Override
public void render(ElementTemplate elementTemplate, Object o, XWPFTemplate xwpfTemplate) {
XWPFRun run = ((RunTemplate) elementTemplate).getRun();
String text = "Hello World!";
run.setText(text, 0);
}
}
测试就跟下方自定义插件生成表格一起了,继续往下学习!!
2 写一个更复杂的插件,在模板标签位置完完全全使用代码创建一个表格
poi-tl提供了抽象模板类
AbstractRenderPolicy
,它定义了一些骨架步骤并且将数据模型的校验和渲染逻辑分开,使用泛型约束数据类型,让插件开发起来更简单,AbstractRenderPolicy实现地也是
RenderPolicy
接口
import com.deepoove.poi.data.style.BorderStyle;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.policy.TableRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.deepoove.poi.util.TableTools;
import com.deepoove.poi.util.UnitUtils;
import com.deepoove.poi.xwpf.BodyContainer;
import com.deepoove.poi.xwpf.BodyContainerFactory;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
public class CustomTableRenderPolicy extends AbstractRenderPolicy<Object> {
@Override
protected void afterRender(RenderContext<Object> renderContext) {
// 清空模板标签所在的段落
clearPlaceholder(renderContext, true);
}
@Override
public void doRender(RenderContext<Object> renderContext) throws Exception {
// 自定义渲染逻辑
XWPFRun run = renderContext.getRun();
BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(run);
// 定义行列
int row = 10;
int col = 8;
XWPFTable table = bodyContainer.insertNewTable(run, row, col);
XWPFParagraph paragraph = bodyContainer.insertNewParagraph(run);
XWPFRun paragraphRun = paragraph.createRun();
paragraphRun.setText("自定义表格");
paragraphRun.setColor("0000FF");
Style style = new Style();
style.setFontSize(18);
// 表格宽度
TableTools.setWidth(table, UnitUtils.cm2Twips(14.63f) + "", null);
// 表格边框和样式
TableTools.borderTable(table, BorderStyle.DEFAULT);
TableTools.mergeCellsHorizonal(table, 0, 0, 7);
TableTools.mergeCellsVertically(table, 1, 1, 9);
}
}
3 测试
@Test
public void testPlugins() throws Exception {
CustomTableRenderPolicy policy = new CustomTableRenderPolicy();
HelloWorldRenderPolicy policy1 = new HelloWorldRenderPolicy();
Configure config = Configure.builder().bind("report", policy)
.bind("title",policy1).build();
XWPFTemplate template = XWPFTemplate.compile("D:\\Idea-projects\\POI_word\\templates_Plugins.docx",config);
Map<String, Object> map = new HashMap<>();
XWPFTemplate render = template.render(map);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Idea-projects\\POI_word\\output_Plugins.docx");
template.writeAndClose(fileOutputStream);
template.close(); // 一定要记得关闭
}
结果