easypoi导出word换行处理

内容包含换行符\n,导出word时换行符失效,会将换行符\n识别为空格。
模板
模板
导出结果
在这里插入图片描述
maven

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.1.2</version>
</dependency>
//数据处理
List<Map<String, Object>> listMap = new ArrayList<>();
Map<String, Object> lm = new HashMap<>();
lm.put("id", 1);
lm.put("name", "维生素D3滴剂");
lm.put("num", 1);
lm.put("yfyl", "每天晚上1滴,随餐服用");
lm.put("yfyl", "维生素 D3 25微克(对应1000iu)");
List<String> gxjsList = Arrays.asList("用于维护骨骼", "支持钙的吸收的利用,维持血液中正常的钙水平", "支持免疫功能");
lm.put("gxjs", StringUtils.join(gxjsList, "\n"));
listMap.add(lm);
Map<String, Object> form = new HashMap<>();
form.put("mapList", listMap);

//easypoi导出word
ClassPathResource classPathResource = new ClassPathResource("templates/prescription_template.docx");
InputStream inputStream = classPathResource.getInputStream();
MyXWPFDocument document = new MyXWPFDocument(inputStream);

WordExportUtil.exportWord07(document, form);
for (XWPFTable table : doc.getTables()) {//表格
    for (XWPFTableRow row : table.getRows()) {//行
        for (XWPFTableCell cell : row.getTableCells()) {
            PdfUtil.addBreakInCell(cell);
        }
    }
}
import org.apache.poi.xwpf.usermodel.*;
public class PdfUtil {
	/**
     * 替换word换行符为中断
     *
     * @param cell
     */
    private static void addBreakInCell(XWPFTableCell cell) {
    	//判断是否包含\n替换为中断
        if (cell.getText() != null && cell.getText().contains("\n")) {
            for (XWPFParagraph p : cell.getParagraphs()) {
                for (XWPFRun run : p.getRuns()) {
                    if (run.getText(0) != null && run.getText(0).contains("\n")) {
                        String[] lines = run.getText(0).split("\n");
                        if (lines.length > 0) {
                            run.setText(lines[0], 0);
                            for (int i = 1; i < lines.length; i++) {
                               //中断
                                run.addBreak(BreakType.TEXT_WRAPPING);
//				                    run.addCarriageReturn();//回车符
                                run.setText(lines[i]);
                            }
                        }
                    }
                }
            }
        }
    }
}
posted @ 2023-07-26 15:28  路暝月  阅读(456)  评论(0编辑  收藏  举报  来源