行跨度与XWPFTable

时间:2014-07-23 10:05:16

标签: java apache-poi xwpf

如何在Java中使用POI中的XWPFTable合并2行或更多行(行跨度)上的单元格?

我知道如何合并一行中的单元格,但我不知道它是怎么做的,我没有找到任何这样的例子。

提前感谢。

1 个答案:

答案 0 :(得分:10)

发现它!感谢您对getCTTc().getTcPr()...this site的评论,这里有一个小程序来测试垂直合并:

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;


public class VerticalMerge {

    public static void main(String[] args) {

        int rows = 5;
        int cols = 5;

        XWPFDocument document = new XWPFDocument();
        XWPFTable table = document.createTable(rows, cols);

        fillTable(table);

        mergeCellsVertically(table, 3, 1, 3);

        try {
            FileOutputStream out = new FileOutputStream("vertical merge.docx");
            document.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void fillTable(XWPFTable table) {
        for (int rowIndex = 0; rowIndex < table.getNumberOfRows(); rowIndex++) {
            XWPFTableRow row = table.getRow(rowIndex);

            for (int colIndex = 0; colIndex < row.getTableCells().size(); colIndex++) {
                XWPFTableCell cell = row.getCell(colIndex);
                cell.addParagraph().createRun().setText(" cell " + rowIndex + colIndex + " ");
            }
        }
    }

    private static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {

        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {

            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);

            if ( rowIndex == fromRow ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

}

目前,它并没有在合并的单元格中连接文本,但我有一个想法,很快就会更新这个答案。祝你好运!