行跨度XWPFTable [英] row span with XWPFTable

查看:571
本文介绍了行跨度XWPFTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能合并单元格在Java中的POI使用XWPFTable 2或多行(行跨度)?

how can I merge cells over 2 or more rows (row span) using XWPFTable in POI in Java?

我知道如何在一列合并单元格,但我不知道如何做到这一点,我不觉得这样的例子。

I know how merge cells in one row but i have no idea how do it and i don't find any example of this.

先谢谢了。

推荐答案

找到了!由于约)自己的评论getCTTc()。getTcPr(... this网站,这里是一个小程序来测试垂直合并:

Found it! Thanks to your own comment about getCTTc().getTcPr()... and this site, here is a little program to test vertical merge:

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);
            }
        }
    }

}

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

For the moment, it doesn't concatenate text in merged cells, but i have an idea and will update this answer soon. Good luck!

这篇关于行跨度XWPFTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆