Java-poi操作doc插入表格,字体设置大小颜色。


    public static void setTableProperties(XWPFTable table) {
        // Set table width (in twentieths of a point)
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        CTTblWidth tblWidth = tblPr.addNewTblW();
        tblWidth.setW(BigInteger.valueOf(7000)); // Adjust the width as needed

        // Set font and color for the entire table
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                for (XWPFParagraph paragraph : cell.getParagraphs()) {
                    for (XWPFRun run : paragraph.getRuns()) {
                        run.setFontFamily("宋体"); // Set font family
                        run.setFontSize(12); // Set font size to 12 points (小四)
                        run.setColor("FF0000"); // Set font color to red
                    }
                }
            }
        }
    }

这段代码为啥设置字体大小和颜色不行呢,宽度倒是可以实现。

【以下回答由 GPT 生成】

这个问题可能是由于缺少运行代码时设置字体属性的步骤引起的。要设置表格中文本的字体大小和颜色,需要创建新的XWPFRun对象并将其添加到段落中的运行列表中。下面是修改后的代码:

public static void setTableProperties(XWPFTable table) {
    // Set table width (in twentieths of a point)
    CTTblPr tblPr = table.getCTTbl().getTblPr();
    CTTblWidth tblWidth = tblPr.addNewTblW();
    tblWidth.setW(BigInteger.valueOf(7000)); // Adjust the width as needed

    // Set font and color for the entire table
    for (XWPFTableRow row : table.getRows()) {
        for (XWPFTableCell cell : row.getTableCells()) {
            for (XWPFParagraph paragraph : cell.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    // Set font family
                    run.setFontFamily("宋体");

                    // Set font size to 12 points (小四)
                    CTRPr ctrPr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();
                    CTHpsMeasure ctHpsMeasure = ctrPr.isSetSz() ? ctrPr.getSz() : ctrPr.addNewSz();
                    ctHpsMeasure.setVal(BigInteger.valueOf(24));

                    // Set font color to red
                    // First, remove existing color settings
                    ctrPr.unsetColorArray();
                    // Then, create a new color object with the specified value
                    CTRPr ctRPr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();
                    CTColor ctColor = ctRPr.addNewColor();
                    ctColor.setVal("FF0000");
                }
            }
        }
    }
}

这个修改后的代码将能够设置表格中文本的字体大小和颜色。请尝试运行代码并验证是否解决了问题。如果问题仍然存在,请提供更多的代码和详细的问题描述,以便我们提供进一步的帮助。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^