我有一个表,我需要为它添加多行,而不是你在图像中看到的变量。我正在使用docx4j。 我改变了这样的变量:
HashMap mappings = new HashMap();
VariablePrepare.prepare(template);
mappings.put("example", "example");
template.getMainDocumentPart().variableReplace(mappings);
答案 0 :(得分:0)
VariableReplace不用于重复数据。
您可以使用OpenDoPE内容控件数据绑定:在表格行周围包装重复内容控件。
https://github.com/plutext/docx4j/blob/master/src/main/java/org/docx4j/model/datastorage/migration/FromVariableReplacement.java可能有助于从VariableReplace迁移到OpenDoPE。
答案 1 :(得分:0)
这对我有用 - 但我的单词模板中没有列标题,所以要小心它们可能会破坏此功能。
只需正确填充HashMap,如果你正确设置了一切就可以开箱即用;)
这些是我用于替换的3个功能:
private void replaceTable(String[] placeholders, List<Map<String, String>> textToAdd, WordprocessingMLPackage template) throws Docx4JException, JAXBException {
List<Object> tables = doc.getAllElementFromObject(template.getMainDocumentPart(), Tbl.class);
Tbl tempTable = getTemplateTable(tables, placeholders[0]);
List<Object> rows = doc.getAllElementFromObject(tempTable, Tr.class);
if (rows.size() == 1) { //careful only tables with 1 row are considered here
Tr templateRow = (Tr) rows.get(0);
for (Map<String, String> replacements : textToAdd) {
addRowToTable(tempTable, templateRow, replacements);
}
assert tempTable != null;
tempTable.getContent().remove(templateRow);
}
}
private void addRowToTable(Tbl reviewTable, Tr templateRow, Map<String, String> replacements) {
Tr workingRow = (Tr) XmlUtils.deepCopy(templateRow);
List<?> textElements = doc.getAllElementFromObject(workingRow, Text.class);
for (Object object : textElements) {
Text text = (Text) object;
String replacementValue = (String) replacements.get(text.getValue());
if (replacementValue != null)
text.setValue(replacementValue);
}
reviewTable.getContent().add(workingRow);
}
private Tbl getTemplateTable(List<Object> tables, String templateKey) throws Docx4JException, JAXBException {
for (Object tbl : tables) {
List<?> textElements = doc.getAllElementFromObject(tbl, Text.class);
for (Object text : textElements) {
Text textElement = (Text) text;
if (textElement.getValue() != null && textElement.getValue().equals(templateKey))
return (Tbl) tbl;
}
}
return null;
}
以下是大致如何将它用于您的示例:
ArrayList<Map<String, String>> list = new ArrayList<>();
//Create a loop here through all entries
Map<String, String> entry = new HashMap<>();
entry.put("${nrCrt}", "1");
list.add(entry);
//...
entry.put("${tva}", "55");
list.add(entry);
entry.put("${nrCrt}", "2");
list.add(entry);
//...
replaceTable(new String[]{"${nrCrt}"}, list, template);
我忘了提及:
doc
只是一个帮助类,这是getAllElementFromObject
:
public List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}