When exporting a word form, the parameters need to be processed with line breaks

When exporting a word form, I encountered a parameter and wanted to change a new line. I tried to use cha(11), /n, /r/n and other operations, but they could not be used.

Later, I found some related codes to solve this problem

Use /n for normal line breaks, use this string of codes before importing templates

                 
       for(XWPFTable table : doc.getTables()) {
            for(XWPFTableRow row : table.getRows()) {
                for(XWPFTableCell cell : row.getTableCells()) {
                    //单元格 : 直接cell.setText()只会把文字加在原有的后面,删除不了文字
                    addBreakInCell(cell);
                }
            }
        }
    private static void addBreakInCell(XWPFTableCell cell) {

        if (cell.getText() != null && cell.getText().contains("\n")) {
            for (XWPFParagraph paragraph : cell.getParagraphs()) {
                paragraph.setAlignment(ParagraphAlignment.LEFT);
                for (XWPFRun run : paragraph.getRuns()) {
                    if (run.getText(0) != null && run.getText(0).contains("\n")) {
                        String[] lines = run.getText(0).split("\n");
                        if (lines.length > 0) {
                            // set first line into XWPFRun
                            run.setText(lines[0], 0);
                            for (int i = 1; i < lines.length; i++) {
                                // add break and insert new text
                                run.addBreak();
                                run.setText(lines[i]);
                            }
                        }
                    }
                }
            }
        }
    }

Guess you like

Origin blog.csdn.net/GuaGea/article/details/129382278