通过先合并多列,再合并行,我们就能达到合并一个区域的效果。
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;
}
}
这里对原方法进行了一些修改:
/// <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