如何通过java给word模板当中的内容进行换行


代码示例

    /**
     * 换行方法
     * @param wordPath word模板的地址
     * @param wordOutPath 换行后输出word的新地址
     */
    public static void wordNewLine(String wordPath,String wordOutPath){
        //获取文档doc
        XWPFDocument doc = null;
        try {
            doc = new XWPFDocument(new FileInputStream(wordPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //遍历所有表格
        for(XWPFTable table : doc.getTables()) {
            for(XWPFTableRow row : table.getRows()) {
                for(XWPFTableCell cell : row.getTableCells()) {
                    //单元格 : 直接cell.setText()只会把文字加在原有的后面,删除不了文字
                    addBreakInCell(cell);
                }
            }
        }
        try {
            doc.write(new FileOutputStream(wordOutPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 匹配单元格内容\n 替换为换行
     * @param 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]);
                            }
                        }
                    }
                }
            }
        }
    }

这里需要注意一点网络上面我测试了/n ,/r,/n/r,包括/r/n都不能完美实现换行,所以最后通过addBreak这个函数实现了函数的换行


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM