C#實現(xiàn)高效生成Word復(fù)雜表格的實戰(zhàn)指南
在現(xiàn)代辦公自動化中,Word 文檔依然是信息呈現(xiàn)和數(shù)據(jù)輸出的重要載體。無論是月度報表、客戶合同,還是內(nèi)部匯總文檔,表格都是不可或缺的元素。手動創(chuàng)建表格不僅效率低,而且容易出錯。借助 C# 編程,我們可以輕松實現(xiàn) Word 表格的自動生成、格式化以及復(fù)雜操作。
本文將系統(tǒng)介紹如何使用 Free Spire.Doc for .NET 處理 Word 表格,包括表格樣式設(shè)置、動態(tài)添加刪除行列、以及單元格內(nèi)嵌套表格等操作。通過這些技巧,您可以快速生成符合業(yè)務(wù)需求的高質(zhì)量文檔。
安裝 Free Spire.Doc for .NET:Install-Package FreeSpire.Doc
1. C# 操作 Word 表格的對象模型
在操作表格之前,需要理解 Word 文檔的對象結(jié)構(gòu):
- Document:文檔整體對象
- Section:文檔的分節(jié),每個 Section 可包含多個段落或表格
- Table:表格對象
- TableRow:表格行
- TableCell:表格單元格
- Paragraph:單元格或正文中的段落
- TextRange:段落中實際文本
- ParagraphStyle:段落樣式,統(tǒng)一管理字體、字號、對齊方式等
掌握這些對象的層級關(guān)系,可以更靈活地控制表格內(nèi)容與樣式。
2. 創(chuàng)建并格式化表格
在很多業(yè)務(wù)場景中,表格不僅需要展示數(shù)據(jù),還要美觀、清晰。下面示例展示如何創(chuàng)建一個銷售數(shù)據(jù)表,設(shè)置列寬、行高、背景色和字體樣式。
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
public class WordTableDemo
{
public static void CreateFormattedTable(string filePath)
{
Document doc = new Document();
Section sec = doc.AddSection();
// 添加標題
Paragraph title = sec.AddParagraph();
TextRange tr = title.AppendText("2025年度產(chǎn)品銷售統(tǒng)計");
tr.CharacterFormat.FontName = "Yu Gothic UI";
tr.CharacterFormat.FontSize = 18;
tr.CharacterFormat.Bold = true;
title.Format.HorizontalAlignment = HorizontalAlignment.Center;
sec.AddParagraph().AppendText("\n"); // 間距
// 創(chuàng)建表格
Table table = sec.AddTable();
table.ResetCells(5, 4); // 5行4列
table.TableFormat.Borders.BorderType = BorderStyle.Single;
table.TableFormat.Borders.LineWidth = 1f;
table.TableFormat.Borders.Color = Color.DarkGray;
// 設(shè)置列寬
int[] colWidths = { 80, 200, 100, 120 };
foreach (TableRow row in table.Rows)
{
for (int i = 0; i < colWidths.Length; i++)
row.Cells[i].SetCellWidth(colWidths[i], CellWidthType.Point);
}
// 表頭樣式
ParagraphStyle headerStyle = doc.AddParagraphStyle("headerStyle");
headerStyle.CharacterFormat.Bold = true;
headerStyle.CharacterFormat.FontName = "Yu Gothic UI";
headerStyle.CharacterFormat.FontSize = 13;
headerStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
string[] headers = { "產(chǎn)品編號", "產(chǎn)品名稱", "銷售數(shù)量", "銷售金額" };
for (int i = 0; i < headers.Length; i++)
{
TableCell cell = table.Rows[0].Cells[i];
cell.CellFormat.BackColor = Color.LightSteelBlue;
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p = cell.AddParagraph();
p.AppendText(headers[i]);
p.ApplyStyle(headerStyle.Name);
}
// 數(shù)據(jù)樣式
ParagraphStyle dataStyle = doc.AddParagraphStyle("dataStyle");
dataStyle.CharacterFormat.FontName = "Yu Gothic UI";
dataStyle.CharacterFormat.FontSize = 12;
dataStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
string[,] data = {
{ "A101", "超薄筆記本", "120", "180000" },
{ "B202", "智能手機", "450", "540000" },
{ "C303", "無線耳機", "300", "90000" },
{ "D404", "智能手表", "200", "80000" }
};
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;
}
}
doc.SaveToFile(filePath, FileFormat.Docx);
Console.WriteLine($"文檔已生成:{filePath}");
}
}
此示例展示了如何創(chuàng)建格式化表格、設(shè)置列寬、行高和背景色,同時應(yīng)用統(tǒng)一字體樣式。
生成結(jié)果預(yù)覽

3. 動態(tài)添加與刪除行列
實際業(yè)務(wù)中,表格行列數(shù)量可能不固定,需要根據(jù)數(shù)據(jù)動態(tài)調(diào)整:
// 添加新行
public static void AddRow(Table table, string[] rowData)
{
TableRow newRow = table.AddRow();
newRow.Height = 22;
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 RemoveRow(Table table, int rowIndex)
{
if (rowIndex >= 0 && rowIndex < table.Rows.Count)
table.Rows.RemoveAt(rowIndex);
}
// 添加列
public static void AddColumn(Table table, int colIndex, string[] colData)
{
for (int r = 0; r < table.Rows.Count; r++)
{
TableCell newCell = new TableCell(table.Document);
table.Rows[r].Cells.Insert(colIndex, newCell);
Paragraph p = newCell.AddParagraph();
if (r < colData.Length) p.AppendText(colData[r]);
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
newCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
}
}
// 刪除列
public static void RemoveColumn(Table table, int colIndex)
{
for (int r = 0; r < table.Rows.Count; r++)
{
if (colIndex >= 0 && colIndex < table.Rows[r].Cells.Count)
table.Rows[r].Cells.RemoveAt(colIndex);
}
}
使用這些方法,表格可以根據(jù)實際數(shù)據(jù)動態(tài)擴展或縮減,非常適合報表和數(shù)據(jù)匯總場景。
4. 單元格內(nèi)嵌套表格
在合同條款、問卷或復(fù)雜布局中,可能需要在一個單元格內(nèi)部嵌入表格:
using Spire.Doc;
using Spire.Doc.Documents;
public class WordTableDemo
{
public static void InsertNestedTable(string filePath)
{
Document doc = new Document();
Section sec = doc.AddSection();
sec.AddParagraph().AppendText("嵌套表格示例").CharacterFormat.FontSize = 16;
sec.AddParagraph().AppendText("\n");
Table outer = sec.AddTable();
outer.ResetCells(2, 2);
outer.TableFormat.Borders.BorderType = BorderStyle.Single;
outer.Rows[0].Cells[0].AddParagraph().AppendText("外表格 (0,0)");
TableCell nestedCell = outer.Rows[0].Cells[1];
nestedCell.AddParagraph().AppendText("內(nèi)部表格如下:");
Table inner = nestedCell.AddTable();
inner.ResetCells(3, 2);
inner.TableFormat.Borders.BorderType = BorderStyle.Dot;
string[,] innerData = {
{ "編號", "名稱" },
{ "001", "筆記本" },
{ "002", "手機" }
};
for (int r = 0; r < innerData.GetLength(0); r++)
{
for (int c = 0; c < innerData.GetLength(1); c++)
{
TableCell cell = inner.Rows[r].Cells[c];
cell.AddParagraph().AppendText(innerData[r, c]);
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
cell.Paragraphs[0].Format.HorizontalAlignment = HorizontalAlignment.Center;
}
}
outer.Rows[1].Cells[0].AddParagraph().AppendText("外表格 (1,0)");
outer.Rows[1].Cells[1].AddParagraph().AppendText("外表格 (1,1)");
doc.SaveToFile(filePath, FileFormat.Docx);
Console.WriteLine($"嵌套表格文檔已生成:{filePath}");
}
static void Main(string[] args)
{
InsertNestedTable("NestedTable.docx");
}
}
嵌套表格能夠在一個單元格內(nèi)呈現(xiàn)多層信息,例如條款編號+說明內(nèi)容,或分區(qū)統(tǒng)計數(shù)據(jù)。
生成結(jié)果預(yù)覽

5. 總結(jié)
本文展示了使用 C# 與 Free Spire.Doc for .NET 操作 Word 表格的多種技巧:
- 創(chuàng)建格式化表格,并統(tǒng)一設(shè)置列寬、行高、背景色和字體樣式
- 動態(tài)添加或刪除行列,適配數(shù)據(jù)量變化
- 在單元格內(nèi)嵌套表格,實現(xiàn)更靈活的文檔布局
通過這些方法,開發(fā)者可以輕松實現(xiàn)高質(zhì)量的 Word 報表、合同或匯總文檔。結(jié)合 Free Spire.Doc 的其他 API,還可擴展圖片插入、分頁控制和 PDF 導(dǎo)出等功能,使文檔生成更智能化。
到此這篇關(guān)于C#實現(xiàn)高效生成Word復(fù)雜表格的實戰(zhàn)指南的文章就介紹到這了,更多相關(guān)C#生成Word復(fù)雜表格內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#使用Stack<T>進行堆棧設(shè)計的實現(xiàn)
堆棧代表了一個后進先出的對象集合,當您需要對各項進行后進先出的訪問時,則使用堆棧,本文主要介紹了C#使用Stack<T>類進行堆棧設(shè)計的實現(xiàn),文中通過示例代碼介紹的非常詳細,感興趣的可以了解一下2024-03-03
C# Directory.GetFiles()函數(shù)案例詳解
這篇文章主要介紹了C# Directory.GetFiles()函數(shù)案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08
C#中結(jié)構(gòu)(struct)的部分初始化和完全初始化實例分析
這篇文章主要介紹了C#中結(jié)構(gòu)(struct)的部分初始化和完全初始化,通過實例分析了結(jié)構(gòu)初始化中常見的錯誤及技巧,有助于加深對C#結(jié)構(gòu)(struct)的認識,需要的朋友可以參考下2014-09-09

