C#插入表格到Word文档
在许多企业应用场景中,Word 文档依旧是最常用的信息呈现与内容输出格式。批量生成合同、输出数据报表、构建结构化文档时,表格往往是不可或缺的组成部分。为了提高效率,使用 C# 自动创建、插入并格式化 Word 表格,已经成为许多系统中的标准能力。
本文将介绍在 C# 中如何以编程方式创建 Word 文档、插入表格、设置样式,并扩展到动态行列与嵌套表格等高级操作。
文中示例基于 Free Spire.Doc for .NET 实现,如需使用,可通过 NuGet 安装:Install-Package FreeSpire.Doc。
1. Word 文档对象模型(基于 Free Spire.Doc for .NET)
要熟练操作表格,了解 Word 文档的对象结构十分重要。Free Spire.Doc for .NET 的 DOM(document Object Model)与 Microsoft Word 文档结构基本一致,主要对象包括:
- document:表示整个 Word 文档
- Section:文档的分节区域,每个 Section 内可以包含多个内容块
- Body:Section 的主体内容区域
- Table:表格对象
- TableRow:表格中的一行
- TableCell:表格单元格
- Paragraph:单元格或正文中的段落
- TextRange:段落中的实际文本
- ParagraphStyle:段落样式,用于统一设置字体、字号、对齐方式等
理解这些对象的层级关系,可以帮助你更灵活地控制表格结构、样式与数据填充。
2. 创建并插入基础表格
下面示例演示如何创建 Word 文档、插入一个固定行列的表格,并填充表头与数据内容。
using Spire.Doc;using Spire.Doc.documents;using Spire.Doc.Fields;public class TableInsertion{ public static void InsertBasicTable(string filePath) { // 创建一个新的Word文档 document document = new document(); Section section = document.AddSection(); // 添加一个段落作为表格的标题 Paragraph titleParagraph = section.AddParagraph(); TextRange tr = titleParagraph.AppendText("产品销售数据表"); titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center; tr.CharacterFormat.FontName = "微软雅黑"; tr.CharacterFormat.FontSize = 16; tr.CharacterFormat.Bold = true; // 添加一个普通段落作为表格前的间距 section.AddParagraph().AppendText("\n"); // 创建一个表格,指定行数和列数 Table table = section.AddTable(); table.ResetCells(5, 4); // 5行4列 // 设置表格的默认边框 table.TableFormat.Borders.BorderType = BorderStyle.Single; table.TableFormat.Borders.LineWidth = 1f; // 创建表头和数据行样式 ParagraphStyle headerStyle = document.AddParagraphStyle("headerStyle"); headerStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; headerStyle.CharacterFormat.FontName = "微软雅黑"; headerStyle.CharacterFormat.FontSize = 14; headerStyle.CharacterFormat.Bold = true; ParagraphStyle dataStyle = document.AddParagraphStyle("dataStyle"); dataStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; dataStyle.CharacterFormat.FontName = "微软雅黑"; dataStyle.CharacterFormat.FontSize = 12; // 填充表格数据 string[] headers = { "产品ID", "产品名称", "销售数量", "销售额" }; string[,] data = { { "P001", "笔记本电脑", "150", "150000" }, { "P002", "智能手机", "300", "210000" }, { "P003", "平板电脑", "100", "80000" }, { "P004", "智能手表", "200", "40000" } }; // 填充表头 for (int i = 0; i < headers.Length; i++) { TableCell cell = table.Rows[0].Cells[i]; Paragraph p = cell.AddParagraph(); p.AppendText(headers[i]); p.ApplyStyle(headerStyle.Name); cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; } // 填充数据行 for (int r = 0; r < data.GetLength(0); r++) { for (int c = 0; c < data.GetLength(1); c++) { TableCell cell = table.Rows[r + 1].Cells[c]; // 从第二行开始填充数据 Paragraph p = cell.AddParagraph(); p.AppendText(data[r, c]); p.ApplyStyle(dataStyle.Name); cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; } } // 保存文档 document.SaveToFile(filePath, FileFormat.Docx); Console.WriteLine($"文档已保存到: {filePath}"); } static void Main(string[] args) { InsertBasicTable("Table.docx"); }}结果文档预览
C#创建Word文档表格
说明
- document → 创建文档对象
- Section → 在文档中添加分节
- AddTable() → 创建表格
- ResetCells(rows, columns) → 指定初始行列数
- cell.AddParagraph().AppendText() → 填充单元格文本
- table.TableFormat.Borders → 设置表格整体边框
该示例适用于结构固定的报表,如月度统计表、产品清单等。
3. 设置表格格式与样式
实际项目中,仅插入表格是不够的,还需要对布局和样式进行控制,以提升可读性。以下示例展示了更复杂的表格格式化过程,包括列宽、行高、背景色、合并单元格和应用段落样式等。
using System.Drawing; // 引入System.Drawing命名空间处理颜色using Spire.Doc;using Spire.Doc.documents;using Spire.Doc.Fields;public class TableFormatting{ public static void FormatComplexTable(string filePath) { document document = new document(); Section section = document.AddSection(); TextRange tr = section.AddParagraph().AppendText("\n复杂表格示例"); tr.CharacterFormat.FontName = "宋体"; tr.CharacterFormat.FontSize = 16; section.AddParagraph().AppendText("\n"); Table table = section.AddTable(); table.ResetCells(5, 5); // 5行4列 // 设置表格的默认边框 table.TableFormat.Borders.BorderType = BorderStyle.Single; table.TableFormat.Borders.LineWidth = 0.5f; table.TableFormat.Borders.Color = Color.LightGray; // 设置列宽 foreach (TableRow row in table.Rows) { row.Cells[0].SetCellWidth(100, CellWidthType.Point); row.Cells[1].SetCellWidth(150, CellWidthType.Point); row.Cells[2].SetCellWidth(80, CellWidthType.Point); row.Cells[3].SetCellWidth(120, CellWidthType.Point); row.Cells[4].SetCellWidth(100, CellWidthType.Point); } // 设置第一行(表头)的格式 TableRow headerRow = table.Rows[0]; headerRow.Height = 25; headerRow.HeightType = TableRowHeightType.Exactly; ParagraphStyle headerStyle = document.AddParagraphStyle("headerStyle"); headerStyle.CharacterFormat.Bold = true; headerStyle.CharacterFormat.FontName = "黑体"; headerStyle.CharacterFormat.FontSize = 13; headerStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; foreach (TableCell cell in headerRow.Cells) { cell.CellFormat.BackColor = Color.FromArgb(192, 192, 192); // 灰色背景 cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph p = cell.AddParagraph(); p.ApplyStyle(headerStyle.Name); } headerRow.Cells[0].Paragraphs[0].AppendText("区域"); headerRow.Cells[1].Paragraphs[0].AppendText("销售经理"); headerRow.Cells[2].Paragraphs[0].AppendText("Q1销售"); headerRow.Cells[3].Paragraphs[0].AppendText("Q2销售"); headerRow.Cells[4].Paragraphs[0].AppendText("总销售额"); // 单元格合并示例:合并第一列的第2、3行 table.ApplyVerticalMerge(0, 1, 2); table.Rows[1].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle; table.Rows[1].Cells[0].AddParagraph().AppendText("华北区"); // 填充数据行 string[,] data = { { "张三", "12000", "15000", "27000" }, { "李四", "10000", "13000", "23000" }, { "王五", "18000", "20000", "38000" }, { "赵六", "16000", "19000", "35000" } }; for (int r = 0; r < data.GetLength(0); r++) { TableRow dataRow = table.Rows[r + 1]; // 从第二行开始,跳过已合并的行 if (r == 0) // 第一行数据对应华北区合并单元格的第二行 { dataRow.Cells[1].AddParagraph().AppendText(data[r, 0]); dataRow.Cells[2].AddParagraph().AppendText(data[r, 1]); dataRow.Cells[3].AddParagraph().AppendText(data[r, 2]); dataRow.Cells[4].AddParagraph().AppendText(data[r, 3]); } else if (r == 1) // 第二行数据对应华北区合并单元格的第三行 { dataRow.Cells[1].AddParagraph().AppendText(data[r, 0]); dataRow.Cells[2].AddParagraph().AppendText(data[r, 1]); dataRow.Cells[3].AddParagraph().AppendText(data[r, 2]); dataRow.Cells[4].AddParagraph().AppendText(data[r, 3]); } else // 其他行正常填充 { // 合并"华南区" table.ApplyVerticalMerge(0, r + 1, 4); table.Rows[r + 1].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle; table.Rows[r + 1].Cells[0].AddParagraph().AppendText("华南区"); table.Rows[r + 1].Cells[0].AddParagraph().Format.HorizontalAlignment = HorizontalAlignment.Center; dataRow = table.Rows[r + 1]; dataRow.Cells[1].AddParagraph().AppendText(data[r, 0]); dataRow.Cells[2].AddParagraph().AppendText(data[r, 1]); dataRow.Cells[3].AddParagraph().AppendText(data[r, 2]); dataRow.Cells[4].AddParagraph().AppendText(data[r, 3]); } foreach (TableCell cell in dataRow.Cells) { cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; if (cell.Paragraphs.Count > 0) cell.Paragraphs[0].Format.HorizontalAlignment = HorizontalAlignment.Center; } } // 确保所有单元格都有段落 foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { if (cell.Paragraphs.Count == 0) { cell.AddParagraph(); } } } // 创建并应用数据行样式 ParagraphStyle dataStyle = document.AddParagraphStyle("dataStyle"); dataStyle.CharacterFormat.FontSize = 12; dataStyle.CharacterFormat.FontName = "黑体"; for (int rowIndex = 1; rowIndex < table.Rows.Count; rowIndex++) { TableRow row = table.Rows[rowIndex]; foreach (TableCell cell in row.Cells) { cell.Paragraphs[0].ApplyStyle(dataStyle.Name); } } document.SaveToFile(filePath, FileFormat.Docx); Console.WriteLine($"格式化文档已保存到: {filePath}"); } static void Main(string[] args) { FormatComplexTable("ComplexTable.docx"); }}结果文档预览
C#设置Word文档表格复杂格式
说明
列宽设置 通过 SetCellWidth() 精确设置列宽,使整体布局更整齐。
行高控制 TableRow.Height 与 HeightType 允许使用固定行高或自适应高度。
背景色与边框 使用 CellFormat.BackColor 和 Borders 提升表格视觉层次。
合并单元格 ApplyVerticalMerge() 和 ApplyHorizontalMerge() 可用于制作更复杂的表头结构。
注意:合并后只有左上角有效单元格可以继续填充内容。
段落样式统一管理 使用 ParagraphStyle 可以对字体、字号、加粗、对齐方式进行统一配置,再通过 p.ApplyStyle() 应用于多个单元格,避免重复设置。
4. 更多表格操作:动态行/列操作与嵌套表格
在数据量不固定的场景(如根据数据库记录生成报表)中,动态添加删除行列、插入嵌套表格等是非常常见的需求。
动态添加/删除行/列
我们可以通过直接操作table.Rows和table.Rows[rowIndex].Cells集合来实现表格行与列的插入、删除等操作。
代码示例
// 动态添加行public static void AddRowToTable(Table table, string[] rowData){ TableRow newRow = table.AddRow(); // 在表格末尾添加新行 newRow.Height = 20; newRow.HeightType = TableRowHeightType.Auto; for (int i = 0; i < rowData.Length; i++) { TableCell cell = newRow.Cells[i]; Paragraph p = cell.AddParagraph(); p.AppendText(rowData[i]); p.Format.HorizontalAlignment = HorizontalAlignment.Center; cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; }}// 动态删除行public static void RemoveRowFromTable(Table table, int rowIndex){ if (rowIndex >= 0 && rowIndex < table.Rows.Count) { table.Rows.RemoveAt(rowIndex); }}// 动态添加列 (逻辑更复杂,需要遍历所有行)public static void AddColumnToTable(Table table, int columnIndex, string[] columnData){ for (int r = 0; r < table.Rows.Count; r++) { TableCell newCell = new TableCell(table.document); table.Rows[r].Cells.Insert(columnIndex, newCell); // 插入新单元格 Paragraph p = newCell.AddParagraph(); if (r < columnData.Length) // 填充数据 { p.AppendText(columnData[r]); } p.Format.HorizontalAlignment = HorizontalAlignment.Center; newCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; }}// 动态删除列 (逻辑更复杂,需要遍历所有行)public static void RemoveColumnFromTable(Table table, int columnIndex){ for (int r = 0; r < table.Rows.Count; r++) { if (columnIndex >= 0 && columnIndex < table.Rows[r].Cells.Count) { table.Rows[r].Cells.RemoveAt(columnIndex); } }}这种方法适用于对已有表格进行行列操作等场景。
创建嵌套表格
在复杂文档结构中(如合同条款、问卷、嵌套布局),可能需要在单元格内部再嵌入一个表格。操作方式与普通表格一致,只是嵌套表格通过:
public static void InsertNestedTable(string filePath){ document document = new document(); Section section = document.AddSection(); section.AddParagraph().AppendText("嵌套表格示例").Format.Font.Size = 16; section.AddParagraph().AppendText("\n"); Table outerTable = section.AddTable(); outerTable.ResetCells(2, 2); outerTable.TableFormat.Borders.BorderType = BorderStyle.Single; // 在外层表格的第一个单元格中插入文本 outerTable.Rows[0].Cells[0].AddParagraph().AppendText("外部表格 - 单元格 (0,0)"); // 在外层表格的第二个单元格中插入嵌套表格 TableCell nestedTableCell = outerTable.Rows[0].Cells[1]; nestedTableCell.AddParagraph().AppendText("嵌套表格在此:"); // 添加一个描述文本 Table innerTable = nestedTableCell.AddTable(); // 在单元格中添加一个新表格 innerTable.ResetCells(3, 2); innerTable.TableFormat.Borders.BorderType = BorderStyle.Dot; // 内部表格边框样式不同 // 填充内部表格数据 innerTable.Rows[0].Cells[0].AddParagraph().AppendText("内部表头1"); innerTable.Rows[0].Cells[1].AddParagraph().AppendText("内部表头2"); innerTable.Rows[1].Cells[0].AddParagraph().AppendText("数据A"); innerTable.Rows[1].Cells[1].AddParagraph().AppendText("数据B"); innerTable.Rows[2].Cells[0].AddParagraph().AppendText("数据C"); innerTable.Rows[2].Cells[1].AddParagraph().AppendText("数据D"); // 设置内部表格单元格格式 foreach (TableRow row in innerTable.Rows) { foreach (TableCell cell in row.Cells) { cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle; if (cell.Paragraphs.Count > 0) cell.Paragraphs[0].Format.HorizontalAlignment = HorizontalAlignment.Center; } } // 继续填充外层表格的其他单元格 outerTable.Rows[1].Cells[0].AddParagraph().AppendText("外部表格 - 单元格 (1,0)"); outerTable.Rows[1].Cells[1].AddParagraph().AppendText("外部表格 - 单元格 (1,1)"); document.SaveToFile(filePath, FileFormat.Docx); Console.WriteLine($"嵌套表格文档已保存到: {filePath}");}插入结果预览:
C#创建Word文档嵌套表格
嵌套表格常用于:
- 条款编号 + 内容的双层结构
- 表格内的说明性结构
- 带标题栏的小型信息块
适当使用嵌套表格可以极大提升复杂文档的布局灵活性。
5. 总结
本文通过多个示例展示了如何使用 C# 和 Free Spire.Doc for .NET 操作 Word 表格,包括:
- 创建文档与插入基础表格
- 控制表格格式、布局和样式
- 动态行列生成适配数据量变化
- 在单元格中嵌套表格构建更灵活的结构
这些功能覆盖了大多数实际业务场景,无论是自动生成合同、构建数据报表,还是制作结构化文档,都可以轻松实现。
如需进一步扩展(如图片插入、分页控制、导出 PDF 等),也可以在此基础上继续组合更多 API 功能。
