Thanks!
The problem is resolved!
I can insert the callback in segments before writing,
The code is as follows:
private static void replaceNodeValue(Node node, String nodeKey, String repVal, FindReplaceOptions findReplaceOptions) throws Exception {
if (Objects.isNull(findReplaceOptions)) {
findReplaceOptions = new FindReplaceOptions();
}
String val = repVal.replaceAll(ControlChar.CR, LINE_KEY).replaceAll(ControlChar.LF, LINE_KEY);
//有换行符分段输出
if (val.contains(LINE_KEY)){
//先替换一遍数据源
String[] split = val.split(LINE_KEY);
List<String> keys = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
String newKey = MessageFormat.format("{0}_{1}",nodeKey,i);
//替换
keys.add(newKey);
}
//占位符替换一遍
node.getRange().replace(nodeKey, StringUtils.join(keys,""), findReplaceOptions);
for (int i = 0; i < split.length; i++) {
String newKey = MessageFormat.format("{0}_{1}",nodeKey,i);
String v = split[i];
FindReplaceOptions thisOptions = new FindReplaceOptions();
if(i != 0){
//第一行不换行
thisOptions.setReplacingCallback(new CustomReplaceEvaluator());
}
//替换
node.getRange().replace(newKey, v, thisOptions);
}
} else {
node.getRange().replace(nodeKey, repVal, findReplaceOptions);
}
}
/**
* 插入换行符回调
*/
private static class CustomReplaceEvaluator implements IReplacingCallback {
@Override
public int replacing(ReplacingArgs e) {
Document document = (Document) e.getMatchNode().getDocument();
DocumentBuilder builder = new DocumentBuilder(document);
Node currentNode = e.getMatchNode();
//将光标移动到此位置
builder.moveTo(currentNode);
//插入换行符
builder.insertBreak(BreakType.LINE_BREAK);
return ReplaceAction.REPLACE;
}
}