Word对象模型 (.Net Perspective)

本文详细介绍如何使用Microsoft Word对象模型创建、格式化Word文档,包括文本、图片和表格的添加方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Word对象模型 (.Net Perspective)
  五大对象
Application:代表Microsoft Word应用程序本身
  是Document和Selection的基类。通过Application的属性和方法,我们可以控制Word的大环境。
Document:代表一个Word文档
  当你新建一个Word文档或者打开一个已有的Word文档,你将创建一个Document对象,该对象被加入到Words Documents Collection中。拥有焦点的Document称为ActiveDocument,可以通过Application对象的ActiveDocument属性获得当前文档对象
Selection :代表当前选中的区域(高亮),没有选中区域时代表光标点
  它通常是高亮显示的(例如,你要改变一段文字的字体,你首先得选中这段文字,那么选中的这块区域就是当前文档的Selection对象所包含的区域)
Bookmarks :书签
  1>书签一般有名字
  2>Saved with the document,且文档关闭了之后书签继续存在
  3>书签通常是隐藏的,但也可以通过代码设置其为可见

Range :代表一块区域,与Selection类似,不过一般不可见
  1>包含一个起始位置和一个结束位置
  2>它可以包含光标点,一段文本或者整个文档
  3>它包含空格,tab以及paragraph marks
  4>它可以是当前选中的区域,当然也可以不是当前选中区域
  5>它被动态创建
  6>当你在一个Range的末尾插入文本,这将扩展该Range


  word文档对象的结构图


关于对象的详细使用,可以参考msdn api

实例使用  

创建Word 文档所使用的主要方法是通过微软公司提供的Microsoft Word X Object Library,
其中X 为版本号。Word2010对应14.0, Word 2007 对应12.0,Word 2003 对应11.0。
通过在项目中添加该组件,即可使用微软公司提供的方法创建相应版本的Word 文档。
在实例中我将所要生成word的格式设置为2003版本

新建一个winForm项目文件,
Com组件中添加 Microsoft Word 12.0 Object Library,引用面板中多出Microsoft.Office.Core、Microsoft.Office.Interop.Word两个引用。
在类文件中添加应用如下:
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;

  下面从word创建、格式设置、文本添加、图片添加、表格添加展示部分代码:

void CreateWord() { object path;//文件路径 string strContent;//文件内容MSWord.Application wordApp;//Word应用程序变量 MSWord.Document wordDoc;//Word文档变量path = "d:\\myWord.doc";//保存为Word2003文档 // path = "d:\\myWord.doc";//保存为Word2007文档 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } //由于使用的是COM 库,因此有许多变量需要用Missing.Value 代替Object Nothing = Missing.Value; //新建一个word对象 wordDoc = wordApp.Documents.Add(refNothing, ref Nothing, ref Nothing, ref Nothing); //WdSaveDocument为Word2003文档的保存格式(文档后缀.doc)\wdFormatDocumentDefault为Word2007的保存格式(文档后缀.docx) object format = MSWord.WdSaveFormat.wdFormatDocument; //将wordDoc 文档对象的内容保存为DOC 文档,并保存到path指定的路径 wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //关闭wordDoc文档wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); //关闭wordApp组件对象wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); Response.Write(""); }

创建Word文档

private void SetWordStyle() { object path;//文件路径 string strContent;//文件内容MSWord.Application wordApp;//Word应用程序变量 MSWord.Document wordDoc;//Word文档变量path = "d:\\myWord.doc";//保存为Word2003文档 // path = "d:\\myWord.doc";//保存为Word2007文档 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //页面设置wordDoc.PageSetup.PaperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4;//设置纸张样式 wordDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//排列方式为垂直方向wordDoc.PageSetup.TopMargin = 57.0f; wordDoc.PageSetup.BottomMargin 57.0f; wordDoc.PageSetup.LeftMargin 57.0f; wordDoc.PageSetup.RightMargin 57.0f; wordDoc.PageSetup.HeaderDistance 30.0f;//页眉位置 //设置页眉wordApp.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;//视图样式wordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成 wordApp.Selection.ParagraphFormat.Alignment =Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //插入页眉图片(测试结果图片未插入成功) wordApp.Selection.ParagraphFormat.Alignment =MSWord.WdParagraphAlignment.wdAlignParagraphCenter; string headerfile = "d:\\header.jpg"; Microsoft.Office.Interop.Word.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, refNothing, ref Nothing, ref Nothing); shape1.Height 20; shape1.Width 80; wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(" 文档页眉"); //去掉页眉的横线wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone; wordApp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible false; wordApp.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;//退出页眉设置 //为当前页添加页码 Microsoft.Office.Interop.Word.PageNumbers pns = wordApp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页的号码 pns.NumberStyle =Microsoft.Office.Interop.Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash; pns.HeadingLevelForChapter 0; pns.IncludeChapterNumber false; pns.RestartNumberingAtSection false; pns.StartingNumber 0object pagenmbetal = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;//将号码设置在中间 object first = true; wordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(refpagenmbetal, ref first); object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordDoc.Close(ref Nothing, refNothing, ref Nothing); wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); Response.Write(""); }

设置Word文档格式

效果图:

 

private void AddWordText() { object path;//文件路径 string strContent;//文件内容MSWord.Application wordApp;//Word应用程序变量 MSWord.Document wordDoc;//Word文档变量path = "d:\\myWord.doc";//保存为Word2003文档 // path = "d:\\myWord.doc";//保存为Word2007文档 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordApp.Selection.ParagraphFormat.LineSpacing = 35f;//设置文档的行间距 //写入普通文本wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行缩进的长度 strContent = "c#向Word写入文本 普通文本:\n"; wordDoc.Paragraphs.Last.Range.Text = strContent; //将文档的前三个字替换成"asdfasdf",并将其颜色设为蓝色 object start = 0object end = 3; Microsoft.Office.Interop.Word.Range rang = wordDoc.Range(ref start, ref end); rang.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBrightGreen; rang.Text "我是替换文字"; wordDoc.Range(ref start, ref end); //写入黑体文本 object unite =Microsoft.Office.Interop.Word.WdUnits.wdStory; wordApp.Selection.EndKey(ref unite, refNothing); wordApp.Selection.ParagraphFormat.FirstLineIndent 0;//取消首行缩进的长度strContent = "黑体文本\n ";//在文本中使用'\n'换行 wordDoc.Paragraphs.Last.Range.Font.Name = "黑体"; wordDoc.Paragraphs.Last.Range.Text = strContent; // wordApp.Selection.Text = strContent; //写入加粗文本 strContent = "加粗文本\n "; wordApp.Selection.EndKey(refunite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Bold 1;//Bold=0为不加粗wordDoc.Paragraphs.Last.Range.Text = strContent; // wordApp.Selection.Text = strContent; //写入15号字体文本 strContent = "15号字体文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Size 15; wordDoc.Paragraphs.Last.Range.Text =strContent; //写入斜体文本 strContent = "斜体文本\n "; wordApp.Selection.EndKey(refunite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Italic 1; wordDoc.Paragraphs.Last.Range.Text = strContent; //写入蓝色文本 strContent = "蓝色文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue; wordDoc.Paragraphs.Last.Range.Text = strContent; //写入下划线文本 strContent = "下划线文本\n "; wordApp.Selection.EndKey(ref unite, ref Nothing); wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick; wordDoc.Paragraphs.Last.Range.Text = strContent; object format =MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing); wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); wordApp.Quit(refNothing, ref Nothing, ref Nothing); Response.Write(""); }

添加文本

效果图:

 

private void AddWordPic() { object path;//文件路径 string strContent;//文件内容MSWord.Application wordApp;//Word应用程序变量 MSWord.Document wordDoc;//Word文档变量path = "d:\\myWord.doc";//保存为Word2003文档 // path = "d:\\myWord.doc";//保存为Word2007文档 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); stringfilename = "d:\\kk.jpg"//定义要向文档中插入图片的位置 object range =wordDoc.Paragraphs.Last.Range; //定义该图片是否为外部链接 object linkToFile = false;//默认 //定义插入的图片是否随word一起保存 object saveWithDocument = true//向word中写入图片wordDoc.InlineShapes.AddPicture(filename, ref Nothing, ref Nothing, ref Nothing);object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory; wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片wordDoc.InlineShapes[1].Height = 130; wordDoc.InlineShapes[1].Width = 200; wordDoc.Content.InsertAfter("\n"); wordApp.Selection.EndKey(ref unite, ref Nothing); wordApp.Selection.ParagraphFormat.Alignment =Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; wordApp.Selection.Font.Size 10;//字体大小 wordApp.Selection.TypeText("图1 测试图片\n"); object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); Response.Write(""); }

添加图片

效果图:

 

private void AddWordTable() { object path;//文件路径 string strContent;//文件内容MSWord.Application wordApp;//Word应用程序变量 MSWord.Document wordDoc;//Word文档变量path = "d:\\myWord.doc";//保存为Word2003文档 // path = "d:\\myWord.doc";//保存为Word2007文档 wordApp = new MSWord.ApplicationClass();//初始化 if (File.Exists((string)path)) { File.Delete((string)path); } Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); inttableRow = 6int tableColumn = 6//定义一个word中的表格对象 MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, refNothing); wordDoc.Tables[1].Cell(11).Range.Text = "列\n行"for (int i = 1; i < tableRow; i++) { for (int j = 1; j < tableColumn; j++) { if (i == 1) { table.Cell(i, j+1).Range.Text = "Column " + j; } if (j == 1) { table.Cell(i+1, j).Range.Text = "Row " + i; } table.Cell(i+1, j+1).Range.Text = i + "行 " + j + ""; } } //添加行table.Rows.Add(ref Nothing); table.Rows[tableRow 1].Height = 45//向新添加的行的单元格中添加图片 string FileName = "d:\\kk.jpg";//图片所在路径 object LinkToFile = false;object SaveWithDocument = trueobject Anchor = table.Cell(tableRow+1, tableColumn).Range;//选中要添加图片的单元格wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 75;//图片宽度wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 45;//图片高度 // 将图片设置为四周环绕型 MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare; //设置table样式 table.Rows.HeightRule =MSWord.WdRowHeightRule.wdRowHeightAtLeast; table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8")); table.Range.Font.Size 10.5F; table.Range.Font.Bold 0; table.Range.ParagraphFormat.Alignment =MSWord.WdParagraphAlignment.wdAlignParagraphCenter; table.Range.Cells.VerticalAlignment =MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom; //设置table边框样式table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble; table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; table.Rows[1].Range.Font.Bold = 1; table.Rows[1].Range.Font.Size = 12F; table.Cell(11).Range.Font.Size = 10.5F; wordApp.Selection.Cells.Height 40;//所有单元格的高度 for(int i = 2; i <= tableRow; i++) { table.Rows[i].Height 20; } table.Cell(11).Range.ParagraphFormat.Alignment =Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; table.Cell(11).Range.Paragraphs[2].Format.Alignment =Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; table.Columns[1].Width = 50for (int i = 2; i <=tableColumn; i++) { table.Columns[i].Width 75; } //添加表头斜线,并设置表头的样式 table.Cell(11).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible = true; table.Cell(11).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color =Microsoft.Office.Interop.Word.WdColor.wdColorGray60; table.Cell(11).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt; //表格边框 //表格内容行边框SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal, Microsoft.Office.Interop.Word.WdColor.wdColorGray20, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth025pt); //表格内容列边框SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical, Microsoft.Office.Interop.Word.WdColor.wdColorGray20, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth025pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); SetTableBorderStyle(table, Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom, Microsoft.Office.Interop.Word.WdColor.wdColorGray50, Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt); //合并单元格 table.Cell(44).Merge(table.Cell(45));//横向合并 table.Cell(23).Merge(table.Cell(43));//纵向合并 object format = MSWord.WdSaveFormat.wdFormatDocument; wordDoc.SaveAs(ref path, refformat, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, refNothing, ref Nothing); wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); Response.Write(""); }

添加表格

附:SetTableBorderStyle函数内容

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

View Code

效果图:

 

书签使用:

使用步骤:1:建立word模板,并且在word中插入要用到的书签

     2:c#方法中新建word操作类,并且打开硬盘中建立好的word模板

     3:找到word模板中的书签,并在书签处写入要插入的数据

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值