使用C#创建Word动态表格及跨文档克隆动态表格的技术问询
Great question! The short answer is: Yes, you absolutely can create a single Word table with dynamic row counts AND variable column counts per row using Table.Add()—you just need a small workaround since the Add() method initially creates a uniform grid. Here's how to pull this off to match your source document's dynamic table structure:
How It Works
Word natively supports tables with varying column counts per row (via cell merging/splitting), but Table.Add() requires you to define a fixed number of rows and columns upfront. The trick is to create a base table with enough columns to accommodate the widest row in your source table, then adjust each row by merging excess cells to match the source's column count.
Step-by-Step Code Implementation
First, make sure you've referenced the Microsoft.Office.Interop.Word assembly in your project. Then use this approach:
using Microsoft.Office.Interop.Word; using System; class WordTableCloner { public static void CloneDynamicTable(Table sourceTable, Range targetRange) { if (sourceTable == null || targetRange == null) throw new ArgumentNullException("Source table or target range cannot be null."); // 1. Calculate total rows and the maximum number of columns in the source table int totalRows = sourceTable.Rows.Count; int maxColumns = 0; foreach (Row row in sourceTable.Rows) { int currentRowCols = row.Cells.Count; if (currentRowCols > maxColumns) maxColumns = currentRowCols; } // 2. Create the base table using Table.Add() (required per your requirement) Table targetTable = targetRange.Tables.Add( Range: targetRange, NumRows: totalRows, NumColumns: maxColumns ); // 3. Adjust each row's column count and copy content for (int rowIndex = 1; rowIndex <= totalRows; rowIndex++) { Row sourceRow = sourceTable.Rows[rowIndex]; Row targetRow = targetTable.Rows[rowIndex]; int sourceColCount = sourceRow.Cells.Count; // Merge excess cells if source row has fewer columns than the base table if (sourceColCount < maxColumns) { // Merge cells starting from the (sourceColCount + 1)th to the last column targetRow.Cells[sourceColCount + 1].Merge(targetRow.Cells[maxColumns]); } // Copy content from source cells to target cells (preserves formatting) for (int colIndex = 1; colIndex <= sourceColCount; colIndex++) { sourceRow.Cells[colIndex].Range.Copy(); targetRow.Cells[colIndex].Range.Paste(); } } } }
Key Notes
- Indexing: Remember that Word's Interop uses 1-based indexing for rows and cells, not 0-based like most C# collections.
- Format Preservation: Using
Copy()andPaste()ensures that cell formatting (like borders, shading, font styles) is carried over from the source. If you only need plain text, replace the copy-paste withtargetRow.Cells[colIndex].Range.Text = sourceRow.Cells[colIndex].Range.Text. - Edge Cases: If your source table has rows with more columns than the initial max (e.g., a later row expands beyond the first row's 7 columns), you can use
Cell.Split()to add columns instead of merging. But based on your description of the source structure, merging will be the primary adjustment needed.
This approach strictly adheres to your requirement of using Table.Add() while fully supporting the dynamic row/column structure of your source Word file.
内容的提问来源于stack exchange,提问作者pravin vala

