当前位置: 首页 > 编程文章 >

C#通过COM组件操作Word文档的完整指南与示例

C#通过COM组件操作Word文档的完整指南与示例

作者:叶宁时间:2025-11-16 17:37:18浏览:209

本文介绍使用VS2008和C#通过Microsoft Word 11.0 Object Library COM组件生成Word文档的方法。需确保系统安装.NET Framework 2.0及Word 2003完全版,并在工程中引用该库。核心在于理解Application、Document等对象模型,并利用Word的“录制宏”功能辅助编写复杂排版代码,如页眉、页码及图文表格处理。

本文目录展开

C#操作Word文档的环境配置与工程设置

近期针对如何利用Visual Studio 2008结合C#语言来输出Word文档进行了研究,现将相关经验总结如下。

整体实现过程相对简便。

开发及运行环境需满足特定条件:操作系统支持Windows XP(需安装.net framework 2.0)、Vista或Win7;且必须安装Word 2003的完全安装版。强调完全安装版的原因在于软件依赖Microsoft word 11.0 Object Library这一COM组件。若未完全安装,可前往微软官网下载并手动安装该组件,文件约4M,下载地址为:http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20923。

在C#工程设置方面,主要步骤是添加COM组件引用。具体操作为:在工程资源管理器中选择"添加引用",切换至"com"选项卡,在下拉列表中找到并选中Microsoft word 11.0 Object Library。虽然界面显示类似添加普通DLL,但VS2008后台已自动处理了.NET调用COM组件的复杂逻辑,开发者无需额外干预。

编码阶段使用Word的COM对象体验流畅,与普通非COM对象无异。为简化代码,建议在源文件顶部添加别名声明:using Word = Microsoft.Office.Interop.Word;。

熟悉Word对象模型有助于减少开发时的困惑。关键对象包括Application、Document、Selection、Range、Bookmark,以及Paragraph、Section、Table等。其中Selection表示当前选择区域或光标位置;Range和Bookmark功能相似但有区别,初学者可通过搜索"word.Range"进一步了解。

6、在写代码的过程中,经常会想要实现的一些操作,但是由于对word对象不熟悉而不知怎么用代码实现。比如设置页眉、添加页码什么的,如果在Word程序里手动的操作当然很简单,但是要用代码来实现,对初学者来说就可能不那么容易了。遇到这种情况,一般有两种方法可以选择:一种是"百度/google法",别一种,也是我所推荐的一种就是,利用Word的“录制宏”功能把想要实现的操作录成宏之后,再看宏里的代码,宏里的代码其实几乎就是你想要的代码了(只不过语法有一点不一样而已)。

下文提供了一个综合示例,涵盖图文、表格、公式的编辑排版,以及页面设置、页眉和页码的处理,代码中包含详细注释,便于理解。


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices; 

namespace WindowsFormsApplication1
{
  public partial class Form1 :System.Windows.Forms. Form
  {

    [DllImport("shell32.dll ")]
    public static extern int ShellExecute(IntPtr hwnd, String lpszOp, String lpszFile, String lpszParams, String lpszDir, int FsShowCmd); 
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //新建文档
      // Word.Application newapp = new Word.Application();//用这句也能初始化
      Word.Application newapp = new Word.ApplicationClass();
      Word.Document newdoc;
      object nothing=System.Reflection.Missing.Value;//用于作为函数的默认参数
      newdoc = newapp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);//生成一个word文档
      newapp.Visible = true ;//是否显示word程序界面

      //页面设置
      //newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape ;
      //newdoc.PageSetup.PageWidth = newapp.CentimetersToPoints(21.0f);
      //newdoc.PageSetup.PageHeight = newapp.CentimetersToPoints(29.7f);
      newdoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;
      newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait;
      newdoc.PageSetup.TopMargin = 57.0f;
      newdoc.PageSetup.BottomMargin = 57.0f;
      newdoc.PageSetup.LeftMargin = 57.0f;
      newdoc.PageSetup.RightMargin = 57.0f;
      newdoc.PageSetup.HeaderDistance = 30.0f;//页眉位置

      //设置页眉
      newapp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;//视图样式。
      newapp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      //插入页眉图片
      string headerfile = "d:\\header.jpg";
      this.outpicture(headerfile, Properties.Resources.header);
      Word.InlineShape shape1= newapp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref nothing, ref nothing, ref nothing);
      shape1.Height = 30;
      shape1.Width = 80;
      newapp.ActiveWindow.ActivePane.Selection.InsertAfter("中建东北院");
      //去掉页眉的那条横线
      newapp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone;
      newapp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false;
      newapp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;//退出页眉设置

      //添加页码
      Word.PageNumbers pns= newapp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;
      pns.NumberStyle = Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
      pns.HeadingLevelForChapter = 0;
      pns.IncludeChapterNumber = false;
      pns.ChapterPageSeparator = Word.WdSeparatorType.wdSeparatorHyphen;
      pns.RestartNumberingAtSection = false;
      pns.StartingNumber = 0;
      object pagenmbetal=Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
      object first=true; 
      newapp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages ].PageNumbers.Add(ref pagenmbetal, ref first);

      //文字设置(Selection表示当前选择集,如果当前没有选择对像,则指对光标所在处进行设置)
      newapp.Selection.Font.Size = 14;
      newapp.Selection.Font.Bold = 0;
      newapp.Selection.Font.Color = Word.WdColor.wdColorBlack;
      newapp.Selection.Font.Name = "宋体";

      //段落设置
      newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
      newapp.Selection.ParagraphFormat.LineSpacing = 20;
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
      newapp.Selection.ParagraphFormat.FirstLineIndent = 30;
      newdoc.Content.InsertAfter( WindowsFormsApplication1.Properties.Resources.PreViewWords);
      
      

      //插入公式
      object oEndOfDoc="\\endofdoc";
      Word.Range rang1 = newdoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
      object fieldType = Word.WdFieldType.wdFieldEmpty;
      object formula = @"eq \i(a,b,ξxdx)";
      object presrveFormatting = false;
      rang1.Text = formula.ToString();
      rang1.Font.Size = 14;
      rang1.Font.Bold = 0;
      rang1.Font.Subscript = 0;
      rang1.Font.Color = Word.WdColor.wdColorBlue;
      rang1.Font.Name = "宋体";
      rang1.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
      rang1.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      newdoc.Fields.Add(rang1, ref fieldType, ref formula, ref presrveFormatting);

      //将文档的前三个字替换成"asdfasdf",并将其颜色设为蓝色
      object start=0;
      object end=3;
      Word.Range rang2 = newdoc.Range(ref start, ref end);
      rang2.Font.Color = Word.WdColor.wdColorBlue;
      rang2.Text = "as签";

      //将文档开头的"as"替换成"袁波"
      rang1.Start = 0;
      rang1.End = 2;
      rang1.Text = "这是一个";
      rang1.InsertAfter("书");
      //rang1.Select();
      object codirection = Word.WdCollapseDirection.wdCollapseStart;
      rang1.Collapse(ref codirection);//将rang1的起点和终点都定于起点或终点

      //对前三个字符进行加粗
      newdoc.Range(ref start, ref end).Bold = 1;
      object rang = rang2;
      newdoc.Bookmarks.Add("yb",ref rang);
      
      
      object unite = Word.WdUnits.wdStory;
      newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
      newapp.Selection.Font.Size = 10;
      newapp.Selection.TypeText("...............................(式1)\n");


      //插入图片
      newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
      //newapp.Selection.HomeKey(ref unite, ref nothing);//将光标移至文开头
      newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      object LinkToFile = false;
      object SaveWithDocument = true;
      object Anchor = newapp.Selection.Range;
      string picname = "d:\\kk.jpg";
      this.outpicture(picname, Properties.Resources.IMG_2169);
      newdoc.InlineShapes.AddPicture(picname, ref LinkToFile, ref SaveWithDocument, ref Anchor);
      newdoc.InlineShapes[1].Height = 200;
      newdoc.InlineShapes[1].Width = 200;
      newdoc.Content.InsertAfter("\n");
      newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.Font.Size = 10;
      newapp.Selection.TypeText("图1 袁冶\n");
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      newdoc.Content.InsertAfter("\n"); 
      newdoc.Content.InsertAfter("\n");

      //用这种方式也可以插入公式,并且这种方法更简单
      newapp.Selection.Font.Size = 14;
      newapp.Selection.InsertFormula(ref formula, ref nothing);
      newapp.Selection.Font.Size = 10;
      newapp.Selection.TypeText("..............................(式2)\n");
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.TypeText("表1 电子产品\n");

      //插入表格
      Word.Table table1 = newdoc.Tables.Add(newapp.Selection.Range, 4, 3, ref nothing, ref nothing);
      newdoc.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";
      newdoc.Tables[1].Cell(1, 2).Range.Text = "电脑";
      newdoc.Tables[1].Cell(1, 3).Range.Text = "手机";
      newdoc.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
      newdoc.Tables[1].Cell(3, 1).Range.Text = "价格(元)";
      newdoc.Tables[1].Cell(4, 1).Range.Text = "共同信息";
      newdoc.Tables[1].Cell(4, 2).Range.Text = "信息A";
      newdoc.Tables[1].Cell(4,3).Range.Text = "信息B";
      

      table1.Select();
      table1.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中
      newapp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
      newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.Cells.HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;
      newapp.Selection.Cells.Height = 40;
      table1.Rows[2].Height = 20;
      table1.Rows[3].Height = 20;
      table1.Rows[4].Height = 20;
      table1.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
      newapp.Selection.Cells.Width=150;
      table1.Columns[1].Width = 75;
      table1.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
      table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

      
      

      //表头斜线
      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown ].Visible = true;
      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Word.WdColor.wdColorGreen;
      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

      //表格边框
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal ].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom ].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop ].Visible = true;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color = Word.WdColor.wdColorGreen;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

      //合并单元格
      newdoc.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));

      //删除图片
      this.delpictfile(headerfile);
      this.delpictfile(picname);


      //保存文档
      object name = "c:\\yb3.doc";
      newdoc.SaveAs(ref name, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
             ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
             ref nothing, ref nothing);
      
      //关闭文档
      object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
      newdoc.Close(ref nothing , ref nothing, ref nothing);
      newapp.Application.Quit(ref saveOption, ref nothing, ref nothing);
      newdoc = null;
      newapp = null;
      ShellExecute(IntPtr.Zero, "open", "c:\\yb3.doc", "", "", 3);
    }

    private void outpicture(string filename,System.Drawing.Bitmap bmap)
    {
      bmap.Save(filename);
    }

    private void delpictfile(string filename)
    {
      System.IO.File.Delete(filename);
    }
   
  }

}
上一篇
Python批量生成本地IP地址并生成批处理文件

该Python脚本通过正则表达式验证IP合法性及分类,自动生成包含多条ipconfig add命令的批处理文件。运行此BAT文件即可将生成的多个本地IP地址绑定到指定网卡,用户可通过ipconfig查看配置结果。

下一篇
Python利用win32com批量生成Word文档

本文介绍如何使用Python的win32com模块通过COM接口连接Microsoft Word,实现批量生成文档的功能。以生成140篇会议记录为例,程序从预设选项中随机组合段落并保存为单页独立的Word文件。文中提供了核心代码片段,并总结了在字体设置和分页符插入方面遇到的细节问题及手动调整经验。

相关文章

更多
PHP通过COM组件读取Word文档的实现方法

本文介绍在PHP开发中利用COM组件读取Word文档的具体实现步骤。首先需在php.ini中启用php_com_dotnet扩展并允许DCOM,随后通过实例化Word.Application对象控制Word进程,设置可见性后打开目标文档,最终提取ActiveDocument的Text属性内容并输出。该方法适用于Windows环境下的自动化文档处理场景。

2025.11.29 589
PHP调用VC编写的COM组件实例

本文介绍如何在Windows环境下通过PHP调用由Visual C++创建的COM组件。首先使用ATL向导创建包含加法功能的COM对象并注册DLL,随后在PHP中启用php_com_dotnet扩展以实例化该组件并调用其方法,实现跨语言交互。

2025.11.16 968
PHP使用imagegrabscreen和imagegrabwindow截取屏幕与窗口缩略图

本文介绍利用PHP的imagegrabscreen和imagegrabwindow函数进行屏幕及窗口截图的方法。通过调用InternetExplorer.Application COM对象,可获取特定窗口或网页内容的图像数据并保存为PNG格式。针对执行后返回纯黑图片的问题,主要原因为非Windows环境不支持该扩展,或Apache服务未开启“允许与桌面交互”权限,需调整服务登录属性解决。

2026.09.17 875
Win2003服务器部署WPS COM组件报错及解决

在Windows Server 2003环境中通过PHP调用WPS Office的COM组件时,常因权限和进程隔离问题导致创建对象失败或远程过程调用错误。主要症状包括“拒绝访问”、“Error [0x800706be] 远程过程调用失败”以及“服务器运行失败”。常规DCAM配置调整交互式用户或指定账户往往无法彻底解决,最终通过将IIS身份验证方式改为使用Administrator管理员账号运行可成功启动组件并避免残留进程。

2025.08.23 841
PHP 5.3连接SQL Server 2000的两种方法:COM与ODBC

本文介绍在PHP 5.3环境下连接SQL Server 2000数据库的两种主要方式。第一种方法利用ADODB.Connection COM对象建立连接,通过provider=sqloledb驱动进行数据交互;第二种方法使用odbc_connect函数配合SQL Server驱动程序实现连接。文中提供了具体的代码示例,展示了如何实例化对象、构建连接字符串、执行查询语句以及遍历结果集获取字段值。

2025.05.12 809
PHP基于模板替换变量生成标准化Word文档

使用 PHPWord 库加载包含占位符的 . docx 模板,通过 setValue 方法替换变量并输出文件。

2025.01.27 740

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。