如何在Java中使用docx-stamper生成Word文档时插入换行符?
docx-stamper 插入换行符的解决方案
docx-stamper 基于Word的XML结构工作,普通的\n或\r\n不会被直接识别为换行,可通过以下两种方式处理:
方法1:直接使用Word原生换行XML标签
在待插入的字符串中使用<w:br/>(Word XML的换行标签),stamper会自动解析并生成换行效果:
import java.io.File; import java.util.HashMap; import java.util.Map; import de.ralleytn.stampfer.DocxStamper; public class DocxStamperDemo { public static void main(String[] args) throws Exception { Map<String, Object> data = new HashMap<>(); // 用<w:br/>分隔多行文本 data.put("multiLineContent", "第一行内容<w:br/>第二行内容<w:br/>第三行内容"); DocxStamper stamper = new DocxStamper(); stamper.stamp(new File("template.docx"), data, new File("output.docx")); } }
方法2:自定义文本处理器自动转换换行符
如果不想手动编写XML标签,可以自定义TextProcessor,将字符串中的\n自动替换为<w:br/>:
import java.io.File; import java.util.HashMap; import java.util.Map; import de.ralleytn.stampfer.DocxStamper; import de.ralleytn.stampfer.DocxStamperConfiguration; import de.ralleytn.stampfer.TextProcessor; public class DocxStamperLineBreakDemo { public static void main(String[] args) throws Exception { // 自定义处理器:将\n替换为Word换行标签 TextProcessor lineBreakProcessor = (text, context) -> text == null ? null : text.replace("\n", "<w:br/>"); DocxStamperConfiguration config = new DocxStamperConfiguration(); config.setTextProcessor(lineBreakProcessor); DocxStamper stamper = new DocxStamper(config); Map<String, Object> data = new HashMap<>(); data.put("multiLineContent", "第一行内容\n第二行内容\n第三行内容"); stamper.stamp(new File("template.docx"), data, new File("output.docx")); } }
注意事项
- 模板中的占位符需使用默认格式(如
${multiLineContent}),确保为纯文本占位,未设置特殊的富文本限制; - 若使用Thymeleaf表达式作为模板语法,需确保表达式解析时保留XML标签的解析能力。
内容的提问来源于stack exchange,提问作者CMS
相关产品推荐
相关产品推荐

