如何通過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