乐趣区

关于poi:Poitl-多级列表渲染

形容

poi-tl 版本 v1.8.2

成果

模板 problem.docx

{{?listMap}}
{{no}}. {{content}}
{{*pictures}}
{{/listMap}}

代码实现


public class PoitlTest {public static void main(String[] args) throws IOException {test();
    }

    private static void test() throws IOException {
        // 创立列表策略
        NumbericRenderPolicy policy = new NumbericRenderPolicy();
        ConfigureBuilder builder = Configure.newBuilder();
        // 为 pictures 指定列表策略
        builder.bind("pictures", policy).build();

        // 多级列表数据,因为列表中可能是 Text 或者 Picture,所以类型采纳 RenderData
        List<RenderData> detailList = new ArrayList<>();
        List<RenderData> detailList2 = new ArrayList<>();
        TextRenderData textRenderData1 = new TextRenderData();
        TextRenderData textRenderData2 = new TextRenderData();
        textRenderData1.setText("选项 1");
        textRenderData2.setText("选项 2");

        BufferedImage bufferedImage1 = ImageIO.read(new URL("https://dev-nfs.sf8cloud.com/receive/EZ-NFS-22a36097-47de-451a-877d-730598ba9166.png"));
        BufferedImage bufferedImage2 = ImageIO.read(new URL("https://dev-nfs.sf8cloud.com/receive/EZ-NFS-c8a9d8fd-9a4b-4376-a44c-00e87030aa71.gif"));

        PictureRenderData pictureRenderData1 = new PictureRenderData(100, 120, ".png",bufferedImage1);
        PictureRenderData pictureRenderData2 = new PictureRenderData(100, 120, ".png",bufferedImage2);
        detailList.add(textRenderData1);
        detailList.add(pictureRenderData1);
        detailList2.add(textRenderData2);
        detailList2.add(pictureRenderData2);

        // 应用 NumbericRenderData 包装列表数据,这样模板中能够间接应用 {{*pictures}} 机型渲染;
        NumbericRenderData numbericRenderData1 = new NumbericRenderData(Pair.of(STNumberFormat.DECIMAL, ""),detailList);
        NumbericRenderData numbericRenderData2 = new NumbericRenderData(Pair.of(STNumberFormat.DECIMAL, ""),detailList2);

        TestPoiMain main = new TestPoiMain();
        List<Map<String, Object>> amapList = new ArrayList<>();
        Map<String, Object> bmap = new HashMap<String, Object>(16);
        bmap.put("pictures", numbericRenderData1);
        bmap.put("no", "A");
        bmap.put("content", "这是一个题目");
        amapList.add(bmap);

        Map<String, Object> bmap2 = new HashMap<String, Object>(16);
        bmap2.put("pictures", numbericRenderData2);
        bmap2.put("no", "B");
        bmap2.put("content", "这是第二个个题目");
        amapList.add(bmap2);

        main.setListMap(amapList);

        XWPFTemplate template = XWPFTemplate.compile("D:\\problem.docx", builder.build()).render(main);
        FileOutputStream out = new FileOutputStream("D:\\output.docx");
        template.write(out);
    }

}
public class TestPoiMain {
    List<Map<String, Object>> listMap;

    public List<Map<String, Object>> getListMap() {return listMap;}

    public void setListMap(List<Map<String, Object>> listMap) {this.listMap = listMap;}
}
退出移动版