最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用C#在Word文檔中插入表格

 更新時(shí)間:2025年11月28日 09:11:20   作者:大丸子  
在許多企業(yè)應(yīng)用場景中,Word 文檔依舊是最常用的信息呈現(xiàn)與內(nèi)容輸出格式,批量生成合同、輸出數(shù)據(jù)報(bào)表、構(gòu)建結(jié)構(gòu)化文檔時(shí),表格往往是不可或缺的組成部分,本文將介紹在 C# 中如何以編程方式創(chuàng)建 Word 文檔、插入表格、設(shè)置樣式,需要的朋友可以參考下

在許多企業(yè)應(yīng)用場景中,Word 文檔依舊是最常用的信息呈現(xiàn)與內(nèi)容輸出格式。批量生成合同、輸出數(shù)據(jù)報(bào)表、構(gòu)建結(jié)構(gòu)化文檔時(shí),表格往往是不可或缺的組成部分。為了提高效率,使用 C# 自動(dòng)創(chuàng)建、插入并格式化 Word 表格,已經(jīng)成為許多系統(tǒng)中的標(biāo)準(zhǔn)能力。

本文將介紹在 C# 中如何以編程方式創(chuàng)建 Word 文檔、插入表格、設(shè)置樣式,并擴(kuò)展到動(dòng)態(tài)行列與嵌套表格等高級操作。

文中示例基于 Free Spire.Doc for .NET 實(shí)現(xiàn),如需使用,可通過 NuGet 安裝:Install-Package FreeSpire.Doc

1. Word 文檔對象模型(基于 Free Spire.Doc for .NET)

要熟練操作表格,了解 Word 文檔的對象結(jié)構(gòu)十分重要。Free Spire.Doc for .NET 的 DOM(Document Object Model)與 Microsoft Word 文檔結(jié)構(gòu)基本一致,主要對象包括:

  • Document:表示整個(gè) Word 文檔
  • Section:文檔的分節(jié)區(qū)域,每個(gè) Section 內(nèi)可以包含多個(gè)內(nèi)容塊
  • Body:Section 的主體內(nèi)容區(qū)域
  • Table:表格對象
  • TableRow:表格中的一行
  • TableCell:表格單元格
  • Paragraph:單元格或正文中的段落
  • TextRange:段落中的實(shí)際文本
  • ParagraphStyle:段落樣式,用于統(tǒng)一設(shè)置字體、字號、對齊方式等

理解這些對象的層級關(guān)系,可以幫助你更靈活地控制表格結(jié)構(gòu)、樣式與數(shù)據(jù)填充。

2. 創(chuàng)建并插入基礎(chǔ)表格

下面示例演示如何創(chuàng)建 Word 文檔、插入一個(gè)固定行列的表格,并填充表頭與數(shù)據(jù)內(nèi)容。

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

public class TableInsertion
{
    public static void InsertBasicTable(string filePath)
    {
        // 創(chuàng)建一個(gè)新的Word文檔
        Document document = new Document();
        Section section = document.AddSection();

        // 添加一個(gè)段落作為表格的標(biāo)題
        Paragraph titleParagraph = section.AddParagraph();
        TextRange tr = titleParagraph.AppendText("產(chǎn)品銷售數(shù)據(jù)表");
        titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
        tr.CharacterFormat.FontName = "微軟雅黑";
        tr.CharacterFormat.FontSize = 16;
        tr.CharacterFormat.Bold = true;

        // 添加一個(gè)普通段落作為表格前的間距
        section.AddParagraph().AppendText("\n");

        // 創(chuàng)建一個(gè)表格,指定行數(shù)和列數(shù)
        Table table = section.AddTable();
        table.ResetCells(5, 4); // 5行4列

        // 設(shè)置表格的默認(rèn)邊框
        table.TableFormat.Borders.BorderType = BorderStyle.Single;
        table.TableFormat.Borders.LineWidth = 1f;

        // 創(chuàng)建表頭和數(shù)據(jù)行樣式
        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;

        // 填充表格數(shù)據(jù)
        string[] headers = { "產(chǎn)品ID", "產(chǎn)品名稱", "銷售數(shù)量", "銷售額" };
        string[,] data = {
            { "P001", "筆記本電腦", "150", "150000" },
            { "P002", "智能手機(jī)", "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;
        }

        // 填充數(shù)據(jù)行
        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]; // 從第二行開始填充數(shù)據(jù)
                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");
    }
}

結(jié)果文檔預(yù)覽

說明

  • Document → 創(chuàng)建文檔對象
  • Section → 在文檔中添加分節(jié)
  • AddTable() → 創(chuàng)建表格
  • ResetCells(rows, columns) → 指定初始行列數(shù)
  • cell.AddParagraph().AppendText() → 填充單元格文本
  • table.TableFormat.Borders → 設(shè)置表格整體邊框

該示例適用于結(jié)構(gòu)固定的報(bào)表,如月度統(tǒng)計(jì)表、產(chǎn)品清單等。

3. 設(shè)置表格格式與樣式

實(shí)際項(xiàng)目中,僅插入表格是不夠的,還需要對布局和樣式進(jìn)行控制,以提升可讀性。以下示例展示了更復(fù)雜的表格格式化過程,包括列寬、行高、背景色、合并單元格和應(yīng)用段落樣式等。

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復(fù)雜表格示例");
        tr.CharacterFormat.FontName = "宋體";
        tr.CharacterFormat.FontSize = 16;
        section.AddParagraph().AppendText("\n");

        Table table = section.AddTable();
        table.ResetCells(5, 5); // 5行4列

        // 設(shè)置表格的默認(rèn)邊框
        table.TableFormat.Borders.BorderType = BorderStyle.Single;
        table.TableFormat.Borders.LineWidth = 0.5f;
        table.TableFormat.Borders.Color = Color.LightGray;

        // 設(shè)置列寬
        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);
        }

        // 設(shè)置第一行(表頭)的格式
        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("區(qū)域");
        headerRow.Cells[1].Paragraphs[0].AppendText("銷售經(jīng)理");
        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("華北區(qū)");

        // 填充數(shù)據(jù)行
        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) // 第一行數(shù)據(jù)對應(yīng)華北區(qū)合并單元格的第二行
            {
                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) // 第二行數(shù)據(jù)對應(yīng)華北區(qū)合并單元格的第三行
            {
                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 // 其他行正常填充
            {
                // 合并"華南區(qū)"
                table.ApplyVerticalMerge(0, r + 1, 4);
                table.Rows[r + 1].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                table.Rows[r + 1].Cells[0].AddParagraph().AppendText("華南區(qū)");
                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();
                }
            }
        }
        // 創(chuàng)建并應(yīng)用數(shù)據(jù)行樣式
        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");
    }
}

結(jié)果文檔預(yù)覽

說明

列寬設(shè)置通過 SetCellWidth() 精確設(shè)置列寬,使整體布局更整齊。

行高控制TableRow.Height 與 HeightType 允許使用固定行高或自適應(yīng)高度。

背景色與邊框使用 CellFormat.BackColor 和 Borders 提升表格視覺層次。

合并單元格ApplyVerticalMerge() 和 ApplyHorizontalMerge() 可用于制作更復(fù)雜的表頭結(jié)構(gòu)。

注意:合并后只有左上角有效單元格可以繼續(xù)填充內(nèi)容。

段落樣式統(tǒng)一管理使用 ParagraphStyle 可以對字體、字號、加粗、對齊方式進(jìn)行統(tǒng)一配置,再通過 p.ApplyStyle() 應(yīng)用于多個(gè)單元格,避免重復(fù)設(shè)置。

4. 更多表格操作:動(dòng)態(tài)行/列操作與嵌套表格

在數(shù)據(jù)量不固定的場景(如根據(jù)數(shù)據(jù)庫記錄生成報(bào)表)中,動(dòng)態(tài)添加刪除行列、插入嵌套表格等是非常常見的需求。

動(dòng)態(tài)添加/刪除行/列

我們可以通過直接操作table.Rowstable.Rows[rowIndex].Cells集合來實(shí)現(xiàn)表格行與列的插入、刪除等操作。

代碼示例

// 動(dòng)態(tài)添加行
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;
    }
}

// 動(dòng)態(tài)刪除行
public static void RemoveRowFromTable(Table table, int rowIndex)
{
    if (rowIndex >= 0 && rowIndex < table.Rows.Count)
    {
        table.Rows.RemoveAt(rowIndex);
    }
}

// 動(dòng)態(tài)添加列 (邏輯更復(fù)雜,需要遍歷所有行)
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) // 填充數(shù)據(jù)
        {
            p.AppendText(columnData[r]);
        }
        p.Format.HorizontalAlignment = HorizontalAlignment.Center;
        newCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
    }
}

// 動(dòng)態(tài)刪除列 (邏輯更復(fù)雜,需要遍歷所有行)
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);
        }
    }
}

這種方法適用于對已有表格進(jìn)行行列操作等場景。

創(chuàng)建嵌套表格

在復(fù)雜文檔結(jié)構(gòu)中(如合同條款、問卷、嵌套布局),可能需要在單元格內(nèi)部再嵌入一個(gè)表格。操作方式與普通表格一致,只是嵌套表格通過:

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;

    // 在外層表格的第一個(gè)單元格中插入文本
    outerTable.Rows[0].Cells[0].AddParagraph().AppendText("外部表格 - 單元格 (0,0)");

    // 在外層表格的第二個(gè)單元格中插入嵌套表格
    TableCell nestedTableCell = outerTable.Rows[0].Cells[1];
    nestedTableCell.AddParagraph().AppendText("嵌套表格在此:"); // 添加一個(gè)描述文本

    Table innerTable = nestedTableCell.AddTable(); // 在單元格中添加一個(gè)新表格
    innerTable.ResetCells(3, 2);
    innerTable.TableFormat.Borders.BorderType = BorderStyle.Dot; // 內(nèi)部表格邊框樣式不同

    // 填充內(nèi)部表格數(shù)據(jù)
    innerTable.Rows[0].Cells[0].AddParagraph().AppendText("內(nèi)部表頭1");
    innerTable.Rows[0].Cells[1].AddParagraph().AppendText("內(nèi)部表頭2");
    innerTable.Rows[1].Cells[0].AddParagraph().AppendText("數(shù)據(jù)A");
    innerTable.Rows[1].Cells[1].AddParagraph().AppendText("數(shù)據(jù)B");
    innerTable.Rows[2].Cells[0].AddParagraph().AppendText("數(shù)據(jù)C");
    innerTable.Rows[2].Cells[1].AddParagraph().AppendText("數(shù)據(jù)D");

    // 設(shè)置內(nèi)部表格單元格格式
    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;
        }
    }

    // 繼續(xù)填充外層表格的其他單元格
    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}");
}

插入結(jié)果預(yù)覽:

嵌套表格常用于:

  • 條款編號 + 內(nèi)容的雙層結(jié)構(gòu)
  • 表格內(nèi)的說明性結(jié)構(gòu)
  • 帶標(biāo)題欄的小型信息塊

適當(dāng)使用嵌套表格可以極大提升復(fù)雜文檔的布局靈活性。

5. 總結(jié)

本文通過多個(gè)示例展示了如何使用 C# 和 Free Spire.Doc for .NET 操作 Word 表格,包括:

  • 創(chuàng)建文檔與插入基礎(chǔ)表格
  • 控制表格格式、布局和樣式
  • 動(dòng)態(tài)行列生成適配數(shù)據(jù)量變化
  • 在單元格中嵌套表格構(gòu)建更靈活的結(jié)構(gòu)

這些功能覆蓋了大多數(shù)實(shí)際業(yè)務(wù)場景,無論是自動(dòng)生成合同、構(gòu)建數(shù)據(jù)報(bào)表,還是制作結(jié)構(gòu)化文檔,都可以輕松實(shí)現(xiàn)。

以上就是使用C#在Word文檔中插入表格的詳細(xì)內(nèi)容,更多關(guān)于C# Word插入表格的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C#中IEnumerable接口的使用

    C#中IEnumerable接口的使用

    C#中的IEnumerable接口是.NET中表示可枚舉集合的核心接口,本文主要介紹了C#中IEnumerable接口的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-12-12
  • C#中將字符串轉(zhuǎn)換為整型的三種解決方法總結(jié)

    C#中將字符串轉(zhuǎn)換為整型的三種解決方法總結(jié)

    本篇文章是對C#中將字符串轉(zhuǎn)換為整型的三種解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • 最新評論

    绥滨县| 彭山县| 神农架林区| 黄大仙区| 永胜县| 大港区| 长阳| 合川市| 商南县| 渝中区| 桑日县| 阳高县| 渭源县| 定陶县| 宜州市| 华阴市| 浮山县| 富平县| 保康县| 宁海县| 麟游县| 沭阳县| 内黄县| 新郑市| 洛川县| 商南县| 桑植县| 兰西县| 石泉县| 饶平县| 安顺市| 雷州市| 扎兰屯市| 若尔盖县| 弋阳县| 克山县| 墨江| 灵丘县| 胶南市| 金沙县| 永福县|