如何使用NPOI的XWPFTable实现合并行的功能

NPOI word 中的单元格合并。网上有不少教程将单元格合并的,但是基本都是在创建的单元的时候就开始合并了。

现在我们来看下,如何在创建好的表格上再做合并动作。

NPOI 的XWPFTable的row提供了MergeCells这个功能,该功能可以实现单行的已存在的单元格的合并,和set gridspan值不一样的是,它不会创建出新的单元格。

但是XWPFTable没有合并多行的方法,这时候我们需要借助CT_Tc 也就是NPOI中表格单元格的另一种表示形式,这种形式可以让你设置单元格的属性(通过将docx解压开,在docx.xml中可以看到,这里不详说了)。

此时,我们给单元格加上Vmerge的属性就可以了。第一个单元格是restart,后面的是continue。

通过先合并多列,再合并行,我们就能达到合并一个区域的效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static XWPFTableCell MYMergeCells(XWPFTable table, int fromCol, int toCol, int fromRow, int toRow)
        {
            for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++)
            {
                if (fromCol < toCol)
                {
                    table.GetRow(rowIndex).MergeCells(fromCol, toCol);
                }
                XWPFTableCell rowcell = table.GetRow(rowIndex).GetCell(fromCol);
                CT_Tc cttc = rowcell.GetCTTc();
                if (cttc.tcPr == null)
                {
                    cttc.AddNewTcPr();
                }
                if (rowIndex == fromRow)
                {
                    // The first merged cell is set with RESTART merge value 
                    rowcell.GetCTTc().tcPr.AddNewVMerge().val = ST_Merge.restart;
                }
                else
                {
                    // Cells which join (merge) the first one, are set with CONTINUE 
                    rowcell.GetCTTc().tcPr.AddNewVMerge().val = ST_Merge.@continue;
                }
            }
 

这里对原方法进行了一些修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// <summary>
      /// 跨行合并
      /// </summary>
      /// <param name="table"></param>
      /// <param name="col">合并的列</param>
      /// <param name="fromRow">起始行</param>
      /// <param name="toRow">终止行</param>
 
      public 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);
 
              CT_Tc cttc = cell.GetCTTc();
              if (cttc.tcPr == null)
              {
                  cttc.AddNewTcPr();
              }
 
 
              //第一个合并单元格用重启合并值设置
              if (rowIndex == fromRow)
              {
                  cell.GetCTTc().AddNewTcPr().AddNewVMerge().val = ST_Merge.restart;
 
              }
              else
              {
                  //合并第一个单元格的单元被设置为“继续”
                  cell.GetCTTc().AddNewTcPr().AddNewVMerge().val = ST_Merge.@continue;
 
              }
 
          }
 
      }
 

这样调用:

粘贴图片

实现效果:

粘贴图片

参考网址: https://blog.csdn.net/weixin_43483847/article/details/87695799

原文地址:https://www.cnblogs.com/cyqdeshenluo/p/12132030.html