poi 复制行格式

发布时间 2023-11-30 11:21:36作者: 烟雨蒙尘
 //oneTitle 是Excel里面设置好的格式,firstTitle 要复制 onTitle的格式
XWPFTableRow firstTitle = workTable.insertNewTableRow(initRow);
createCellsAndCopyStyles(firstTitle, oneTitle,true);


/** * 复制单元格和样式 * * @param targetRow 要复制的行 * @param sourceRow 被复制的行 * @param copyValue 是否复制值 true 复制, false 不复制 */ public static void createCellsAndCopyStyles(XWPFTableRow targetRow, XWPFTableRow sourceRow,boolean copyValue) { targetRow.getCtRow().setTrPr(sourceRow.getCtRow().getTrPr()); List<XWPFTableCell> tableCells = sourceRow.getTableCells(); if (CollectionUtil.isEmpty(tableCells)) { return; } for (XWPFTableCell sourceCell : tableCells) { XWPFTableCell newCell = targetRow.addNewTableCell(); if (copyValue){ newCell.setText(sourceCell.getText()); } newCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr()); List sourceParagraphs = sourceCell.getParagraphs(); if (CollectionUtil.isEmpty(sourceParagraphs)) { continue; } XWPFParagraph sourceParagraph = (XWPFParagraph) sourceParagraphs.get(0); List targetParagraphs = newCell.getParagraphs(); XWPFParagraph targetParagraph = CollectionUtil.isEmpty(targetParagraphs) ? newCell.addParagraph() : (XWPFParagraph) targetParagraphs.get(0); targetParagraph.getCTP().setPPr(sourceParagraph.getCTP().getPPr()); XWPFRun targetRun = targetParagraph.getRuns().isEmpty() ? targetParagraph.createRun() : targetParagraph.getRuns().get(0); List<XWPFRun> sourceRunList=sourceParagraph.getRuns(); if (CollectionUtil.isNotEmpty(sourceRunList)) { XWPFRun sourceRun=sourceRunList.get(0); //字体名称 targetRun.setFontFamily(sourceRun.getFontFamily()); //字体大小 targetRun.setFontSize(sourceRun.getFontSize()); //字体颜色 targetRun.setColor(sourceRun.getColor()); //字体加粗 targetRun.setBold(sourceRun.isBold()); //字体倾斜 targetRun.setItalic(sourceRun.isItalic()); } } }

相关的依赖

        <!--生成word需要的依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!--html富文本转word-->
        <dependency>
            <groupId>io.github.draco1023</groupId>
            <artifactId>poi-tl-ext</artifactId>
            <version>0.4.3</version>
        </dependency>