C# Word 开发:拆分表格列为两列
可以使用以下代码实现将表格中某一列拆分成两列:
// 获取表格对象
Table table = document.Tables[1];
// 获取要拆分的列对象
Column column = table.Columns[2];
// 获取列中的所有单元格
IEnumerable<Cell> cells = column.Cells;
// 将列中的单元格分成两组
IEnumerable<Cell>[] cellGroups = cells.Partition(2);
// 创建新的列对象并插入到表格中
Column newColumn = table.Columns.Add();
int newColumnIndex = table.Columns.IndexOf(newColumn);
// 将第一组单元格移到新的列中
foreach (Cell cell in cellGroups[0])
{
int rowIndex = cell.RowIndex;
table.Cell(rowIndex, newColumnIndex).Range.FormattedText = cell.Range.FormattedText;
}
// 将第二组单元格插入到新的列中
foreach (Cell cell in cellGroups[1])
{
int rowIndex = cell.RowIndex;
table.Cell(rowIndex, newColumnIndex + 1).Range.FormattedText = cell.Range.FormattedText;
}
// 删除原有的列对象
table.Columns.Remove(column);
其中,document 是 Word 文档对象,table 表示要操作的表格对象,column 表示要拆分的列对象。该代码将拆分出来的新列插入到原有列的右侧,拆分后会删除原有列对象。
原文地址: https://www.cveoy.top/t/topic/nuIQ 著作权归作者所有。请勿转载和采集!