在模板docx4java中插入表格

时间:2019-12-05 12:41:37

标签: java spring docx4j

我目前正在尝试在模板的中间而不是最后插入表格/数据(没关系)。那有可能吗?我不想创建createPackage,但正如我所说,我想加载一个模板并放置在模板的中间,以便插入数据,并使其他部分保持不变。

public byte[] generateDocxFileFromTemplate(UserInformation userInformation) throws Exception {

    InputStream templateInputStream = this.getClass().getClassLoader().getResourceAsStream(TEMPLATE_NAME);

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

    VariablePrepare.prepare(wordMLPackage);

    HashMap<String, String> variables = new HashMap<>();
    variables.put("numeCont", String.valueOf(userInformation.getNumeCont()));
    variables.put("ibanCont", String.valueOf(userInformation.getIbanCont()));
    variables.put("dataSfarsit", String.valueOf(userInformation.getDataSfarsit()));
    variables.put("dataInceput", String.valueOf(userInformation.getDataInceput()));

    documentPart.variableReplace(variables);

    //table side
    ObjectFactory factory = Context.getWmlObjectFactory();
    P p1 = factory.createP();
    R r1 = factory.createR();
    Text t1 = factory.createText();
    t1.setValue("String");
    r1.getContent().add(t1);
    p1.getContent().add(r1);

    //part4
    int writableWidthTwips = wordMLPackage.getDocumentModel()
            .getSections().get(0).getPageDimensions().getWritableWidthTwips();
    int columnNumber = 3;
    Tbl tbl = TblFactory.createTable(userInformation.getList().size(), userInformation.getList().get(0).size(), writableWidthTwips/columnNumber);


    List<Object> rows = tbl.getContent();
    for (Object row : rows) {
        Tr tr = (Tr) row;
        List<Object> cells = tr.getContent();
        for(Object cell : cells) {
            Tc td = (Tc) cell;
            td.getContent().add(p1);
        }
    }

    addBorders(tbl);
    documentPart.getContent().add(tbl);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    wordMLPackage.save(outputStream);

    return outputStream.toByteArray();
}

0 个答案:

没有答案