使用 C# 自动创建和格式化 Word 表格

要在 C# 中自动创建和格式化 Word 表格,可借助Microsoft.Office.Interop.Word库或DocX(更轻量,无需安装 Office)。以下分别介绍两种方案的实现方法:

方案一:使用 Microsoft.Office.Interop.Word(需安装 Office)

1. 安装依赖

通过 NuGet 安装Microsoft.Office.Interop.Word包(或手动引用 COM 组件Microsoft Word xx.x Object Library)。

2. 示例代码:创建并格式化表格

csharp
 
运行
 
 
 
 
using Microsoft.Office.Interop.Word;
using System;

class WordTableCreator
{
    static void Main()
    {
        // 创建Word应用程序实例
        Application wordApp = new Application();
        wordApp.Visible = true; // 显示Word窗口

        // 创建新文档
        Document doc = wordApp.Documents.Add();

        // 在文档末尾插入表格(3行4列)
        Table table = doc.Tables.Add(
            Range: doc.Range(), 
            NumRows: 3, 
            NumColumns: 4
        );

        // 设置表格样式
        table.Style = "Table Grid"; // 使用内置网格样式
        table.Borders.Enable = 1; // 启用边框

        // 填充表头
        table.Cell(1, 1).Range.Text = "姓名";
        table.Cell(1, 2).Range.Text = "年龄";
        table.Cell(1, 3).Range.Text = "部门";
        table.Cell(1, 4).Range.Text = "入职日期";

        // 填充数据行
        table.Cell(2, 1).Range.Text = "张三";
        table.Cell(2, 2).Range.Text = "28";
        table.Cell(2, 3).Range.Text = "研发部";
        table.Cell(2, 4).Range.Text = "2023-01-15";

        table.Cell(3, 1).Range.Text = "李四";
        table.Cell(3, 2).Range.Text = "32";
        table.Cell(3, 3).Range.Text = "市场部";
        table.Cell(3, 4).Range.Text = "2022-05-20";

        // 格式化表头(加粗、居中)
        foreach (Cell cell in table.Rows[1].Cells)
        {
            cell.Range.Bold = 1; // 加粗
            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; // 居中
            cell.Shading.BackgroundPatternColor = WdColor.wdColorLightGray; // 背景色
        }

        // 设置单元格内边距
        table.CellPadding = 10;

        // 调整列宽(第1列宽度设为80pt,第2列100pt)
        table.Columns[1].Width = wordApp.InchesToPoints(1); // 1英寸=72pt
        table.Columns[2].Width = wordApp.InchesToPoints(1.5f);

        // 保存文档
        string filePath = @"C:\Temp\WordTableDemo.docx";
        doc.SaveAs2(filePath);

        // 释放资源
        doc.Close();
        wordApp.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(table);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);

        Console.WriteLine("Word表格创建完成!");
    }
}
 

方案二:使用 DocX(无需安装 Office)

1. 安装依赖

通过 NuGet 安装DocX包(DocX由 Xceed 开发,轻量级且跨平台)。

2. 示例代码:创建并格式化表格

csharp
 
运行
 
 
 
 
using DocX;
using System;
using System.Drawing;

class DocXTableCreator
{
    static void Main()
    {
        // 创建新文档
        using (DocX document = DocX.Create(@"C:\Temp\DocXTableDemo.docx"))
        {
            // 添加标题
            document.InsertParagraph("员工信息表").FontSize(15).Bold().SpacingAfter(20);

            // 创建表格(3行4列)
            Table table = document.AddTable(3, 4);
            table.Design = TableDesign.LightGridAccent1; // 表格样式

            // 填充表头
            table.Rows[0].Cells[0].Paragraphs.First().Append("姓名").Bold();
            table.Rows[0].Cells[1].Paragraphs.First().Append("年龄").Bold();
            table.Rows[0].Cells[2].Paragraphs.First().Append("部门").Bold();
            table.Rows[0].Cells[3].Paragraphs.First().Append("入职日期").Bold();

            // 填充数据行
            table.Rows[1].Cells[0].Paragraphs.First().Append("张三");
            table.Rows[1].Cells[1].Paragraphs.First().Append("28");
            table.Rows[1].Cells[2].Paragraphs.First().Append("研发部");
            table.Rows[1].Cells[3].Paragraphs.First().Append("2023-01-15");

            table.Rows[2].Cells[0].Paragraphs.First().Append("李四");
            table.Rows[2].Cells[1].Paragraphs.First().Append("32");
            table.Rows[2].Cells[2].Paragraphs.First().Append("市场部");
            table.Rows[2].Cells[3].Paragraphs.First().Append("2022-05-20");

            // 格式化表头(居中、背景色)
            foreach (TableCell cell in table.Rows[0].Cells)
            {
                cell.Paragraphs.First().Alignment = Alignment.center;
                cell.FillColor = Color.LightGray;
            }

            // 设置列宽
            table.SetColumnWidth(0, 80);
            table.SetColumnWidth(1, 60);
            table.SetColumnWidth(2, 100);
            table.SetColumnWidth(3, 100);

            // 将表格插入文档
            document.InsertTable(table);

            // 保存文档
            document.Save();
        }

        Console.WriteLine("DocX表格创建完成!");
    }
}
 

关键功能说明

  1. 表格创建:指定行列数生成表格,填充文本内容。
  2. 样式格式化
    • 边框、背景色、对齐方式(居中 / 左对齐)
    • 字体样式(加粗、字号)
    • 列宽、单元格内边距调整
  3. 资源释放:使用Interop时需手动释放 COM 对象,避免内存泄漏;DocX使用using自动释放。

注意事项

  • Interop 方案:需安装 Microsoft Office,且版本需与引用的 COM 组件匹配。
  • DocX 方案:无需 Office,适合服务器环境,但高级格式支持略少于 Interop。
posted @ 2025-11-26 20:17  老程序员888  阅读(0)  评论(0)    收藏  举报