目录
1、文档说明
本文档主要介绍如何在程序中操作Word,下面的实例讲述了操作Word的几个关键点。
2、实例说明
2.1、添加引用
在VS打开项目的解决方案资源管理器中,右击引用,选择添加引用,出现添加引用对话框,选择COM标签,然后在下面的框中找到"Microsoft Word 11.0 Object Lib…",然后依次点击右边的"选择"按钮和下面的"确定"按钮,添加应用完成。
2.2、定义Word.Application 对象
Word.Application WordApp = new Word.ApplicationClass();
2.3、打开文档
doc = WordApp.Documents.Open(
ref template, ref missing,ref readOnly,ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
2.4、新建文档
doc = WordApp.Documents.Add( ref template, ref missing,ref readOnly,ref missing );
2.5、设置页眉文本
WordApp.ActiveWindow.ActivePane.View.SeekView
= Word.WdSeekView.wdSeekCurrentPageHeader;
WordApp.Selection.WholeStory();
WordApp.Selection.TypeText( this.m_titleText );
WordApp.ActiveWindow.ActivePane.View.SeekView
= Word.WdSeekView.wdSeekMainDocument;
2.6、页面设置,设置页面为纵向布局,设置纸张类型为A4纸
doc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
doc.PageSetup.PageWidth = WordApp.CentimetersToPoints(29.7F);
doc.PageSetup.PageHeight = WordApp.CentimetersToPoints(21F);
2.7、创建表格及设置表格和单元格属性
object autoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitWindow;
doc.Content.Tables.Add(
WordApp.Selection.Range,
totalCount + 1,
totalField - keyCount_1,
ref missing,
ref autoFitBehavior);
2.8、获取文档中的表格
Word.Table myTable=doc.Tables[1];
2.9、合并单元隔
doc.Content.Tables[1].Cell(i+1,j).Select();
object moveUnit = Word.WdUnits.wdLine;
object moveCount = 1;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveUp(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
doc.Content.Tables[1].Cell(i+1,1).Range.Text = "单元格内容填充"
2.10、添加表格行
doc.Content.Tables[0].Rows.Add(ref beforeRow);
2.11、添加表格列
doc.Content.Tables[0].Columns.Add(ref beforeColumn);
2.12、文本居中
WordApp.Selection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.Selection.Cells.VerticalAlignment =
Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//选中单元格文字垂直居中
2.13、保存Word
doc.SaveAs(ref filename,ref missing ,ref missing ,ref missing ,ref missing,ref missing ,ref missing ,ref missing ,ref missing ,ref missing ,ref missing ,ref missing ,ref missing ,ref missing ,ref missing ,ref missing );
2.14、结束Word进程
myDoc.Close (ref missing,ref missing ,ref missing);
myWord.Quit (ref missing,ref missing ,ref missing );