前面的准备工作

本文中用C#来操作Word,包括:

创建Word;

插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等;

设置段落的首行缩进、行距;

设置页面页边距和纸张大小;

设置页眉、页码;

插入图片,设置图片宽高以及给图片添加标题;

插入表格,格式化表格,往表格中插入数据;

保存Word,打印Word;

重新打开Word等。

Visual studio版本:Visual Studio 2013(2010应该也可以)

准备工作:

/*

添加引用COM里面的 Microsoft Word 12.0 Object. Library 引用(12.0表示Word 2007版本)

导命名空间
using MSWord =Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;

把引用中的Microsoft.Office.Interop.Word的“属性”中的嵌入互操作设为False

存在的Bug:在关闭时,应该采用互操作把Word进程 Kill 掉,精准捕获对应的word

*/
补记:当关闭对应的程序时,还应关闭对应的进程,精确捕获对应的进程函数原型为:(不知道为什么无法找到Word的函数句柄)

  public void ClosePro(Excel.Application xlApp, Excel.Workbook xlsWorkBook);

实现了杀死对应的进程,不会驻留在内存中。
实现程序为:

  [DllImport("User32.dll", CharSet = CharSet.Auto)]public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);public void ClosePro(Excel.Application xlApp, Excel.Workbook xlsWorkBook){if (xlsWorkBook != null)xlsWorkBook.Close(true, Type.Missing, Type.Missing);xlApp.Quit();// 安全回收进程System.GC.GetGeneration(xlApp);IntPtr t = new IntPtr(xlApp.Hwnd);   //获取句柄int k = 0;GetWindowThreadProcessId(t, out k);   //获取进程唯一标志            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);p.Kill();     //关闭进程}

正式开始

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;namespace Console_WordSkill_All
{class Program{static void Main(string[] args){object path;                              //文件路径变量string strContent;                        //文本内容变量MSWord.Application wordApp;                   //Word应用程序变量 MSWord.Document wordDoc;                  //Word文档变量path = Environment.CurrentDirectory + "\\MyWord_Print.doc";wordApp = new MSWord.ApplicationClass(); //初始化wordApp.Visible = true;//使文档可见//如果已存在,则删除if (File.Exists((string)path)){File.Delete((string)path);}//由于使用的是COM库,因此有许多变量需要用Missing.Value代替Object Nothing = Missing.Value;wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);#region 页面设置、页眉图片和文字设置,最后跳出页眉设置//页面设置wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//设置纸张样式为A4纸wordDoc.PageSetup.Orientation = MSWord.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 = MSWord.WdViewType.wdNormalView;//普通视图(即页面视图)样式wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐//插入页眉图片(测试结果图片未插入成功)wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;string headerfile = @"C:\Users\xiahui\Desktop\OficeProgram\3.jpg";MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing);shape1.Height = 5;//强行设置貌似无效,图片没有按设置的缩放——图片的比例并没有改变。shape1.Width = 20;wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("  文档页眉");//在页眉的图片后面追加几个字//去掉页眉的横线wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone;wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false;wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;//退出页眉设置#endregion#region 页码设置并添加页码//为当前页添加页码MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页的号码pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//设置页码的风格,是Dash形还是圆形的pns.HeadingLevelForChapter = 0;pns.IncludeChapterNumber = false;pns.RestartNumberingAtSection = false;pns.StartingNumber = 0; //开始页页码?object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//将号码设置在中间object first = true;wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);#endregion#region 行间距与缩进、文本字体、字号、加粗、斜体、颜色、下划线、下划线颜色设置wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//设置文档的行间距wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行缩进的长度//写入普通文本strContent = "我是普通文本\n";wordDoc.Paragraphs.Last.Range.Text = strContent;wordDoc.Paragraphs.Last.Range.Text = "我再加一行试试,这里不加'\\n'";//直接添加段,不是覆盖( += )wordDoc.Paragraphs.Last.Range.Text += "不会覆盖的,";//添加在此段的文字后面,不是新段落wordDoc.Paragraphs.Last.Range.InsertAfter("这是后面的内容\n");//将文档的前4个字替换成"哥是替换文字",并将其颜色设为红色object start = 0;object end = 4;MSWord.Range rang = wordDoc.Range(ref start, ref end);rang.Font.Color = MSWord.WdColor.wdColorRed;rang.Text = "哥是替换文字";wordDoc.Range(ref start, ref end);//写入黑体文本object unite = MSWord.WdUnits.wdStory;wordApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到文本末尾wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行缩进的长度strContent = "这是黑体文本\n";wordDoc.Paragraphs.Last.Range.Font.Name = "黑体";wordDoc.Paragraphs.Last.Range.Text = strContent;//写入加粗文本strContent = "这是粗体文本\n"; //wordApp.Selection.EndKey(ref unite, ref Nothing);//这一句不加,有时候好像也不出问题,不过还是加了安全wordDoc.Paragraphs.Last.Range.Font.Bold = 1;wordDoc.Paragraphs.Last.Range.Text = strContent;//写入15号字体文本strContent = "我这个文本的字号是15号,而且是宋体\n";wordApp.Selection.EndKey(ref unite, ref Nothing);wordDoc.Paragraphs.Last.Range.Font.Size = 15;wordDoc.Paragraphs.Last.Range.Font.Name = "宋体";wordDoc.Paragraphs.Last.Range.Text = strContent;//写入斜体文本strContent = "我是斜体字文本\n";wordApp.Selection.EndKey(ref unite, 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;//写入红色下画线文本strContent = "我是点线下划线,并且下划线是红色的\n";wordApp.Selection.EndKey(ref unite, ref Nothing);wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineDottedHeavy;wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;wordDoc.Paragraphs.Last.Range.Text = strContent;//取消下划线,并且将字号调整为12号strContent = "我他妈不要下划线了,并且设置字号为12号,黑色不要斜体\n";wordApp.Selection.EndKey(ref unite, ref Nothing);wordDoc.Paragraphs.Last.Range.Font.Size = 12;wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone;wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack;wordDoc.Paragraphs.Last.Range.Font.Italic = 0;wordDoc.Paragraphs.Last.Range.Text = strContent;#endregion#region 插入图片、居中显示,设置图片的绝对尺寸和缩放尺寸,并给图片添加标题wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾//图片文件的路径string filename = Environment.CurrentDirectory + "\\6.jpg";//要向Word文档中插入图片的位置Object range = wordDoc.Paragraphs.Last.Range;//定义该插入的图片是否为外部链接Object linkToFile = false;               //默认,这里貌似设置为bool类型更清晰一些//定义要插入的图片是否随Word文档一起保存Object saveWithDocument = true;              //默认//使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入图片wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片//设置图片宽高的绝对大小//wordDoc.InlineShapes[1].Width = 200;//wordDoc.InlineShapes[1].Height = 150;//按比例缩放大小wordDoc.InlineShapes[1].ScaleWidth = 20;//缩小到20% ?wordDoc.InlineShapes[1].ScaleHeight = 20;//在图下方居中添加图片标题wordDoc.Content.InsertAfter("\n");//这一句与下一句的顺序不能颠倒,原因还没搞透wordApp.Selection.EndKey(ref unite, ref Nothing);          wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;wordApp.Selection.Font.Size = 10;//字体大小wordApp.Selection.TypeText("图1 测试图片\n");#endregion#region 添加表格、填充数据、设置表格行列宽高、合并单元格、添加表头斜线、给单元格添加图片wordDoc.Content.InsertAfter("\n");//这一句与下一句的顺序不能颠倒,原因还没搞透wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;//object WdLine2 = MSWord.WdUnits.wdLine;//换一行;  //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行输入表格,这样表格就在文字下方了,不过这是非主流的方法//设置表格的行数和列数int tableRow = 6;int tableColumn = 6;//定义一个Word中的表格对象MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,tableRow, tableColumn, ref Nothing, ref Nothing);//默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框 table.Borders.Enable = 1;//这个值可以设置得很大,例如5、13等等//表格的索引是从1开始的。wordDoc.Tables[1].Cell(1, 1).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 = 35;//设置新增加的这行表格的高度//向新添加的行的单元格中添加图片string FileName = Environment.CurrentDirectory + "\\6.jpg";//图片所在路径object LinkToFile = false;object SaveWithDocument = true;object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//选中要添加图片的单元格wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);//由于是本文档的第2张图,所以这里是InlineShapes[2]wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//图片宽度wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//图片高度// 将图片设置为四周环绕型MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].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(1, 1).Range.Font.Size = 10.5F;wordApp.Selection.Cells.Height = 30;//所有单元格的高度//除第一行外,其他行的行高都设置为20for (int i = 2; i <= tableRow; i++){table.Rows[i].Height = 20;}//将表格左上角的单元格里的文字(“行” 和 “列”)居右table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//将表格左上角的单元格里面下面的“列”字移到左边,相比上一行就是将ParagraphFormat改成了Paragraphs[2].Formattable.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;table.Columns[1].Width = 50;//将第 1列宽度设置为50//将其他列的宽度都设置为75for (int i = 2; i <= tableColumn; i++){table.Columns[i].Width = 75;}//添加表头斜线,并设置表头的样式table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true;table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed;table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt;//合并单元格table.Cell(4, 4).Merge(table.Cell(4, 5));//横向合并table.Cell(2, 3).Merge(table.Cell(4, 3));//纵向合并,合并(2,3),(3,3),(4,3)#endregionwordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾wordDoc.Content.InsertAfter("\n");wordDoc.Content.InsertAfter("就写这么多,算了吧!2016.09.27");//WdSaveFormat为Word 2003文档的保存格式object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault//将wordDoc文档对象的内容保存为DOCX文档wordDoc.SaveAs(ref path, ref format, 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);//关闭wordDoc文档对象//看是不是要打印//wordDoc.PrintOut();wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);//关闭wordApp组件对象wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);Console.WriteLine(path + " 创建完毕!");Console.ReadKey();//我还要打开这个文档玩玩MSWord.Application app = new MSWord.Application();MSWord.Document doc = null;try{object unknow = Type.Missing;app.Visible = true;string str = Environment.CurrentDirectory + "\\MyWord_Print.doc";object file = str;doc = app.Documents.Open(ref file,ref unknow, ref unknow, ref unknow, ref unknow,ref unknow, ref unknow, ref unknow, ref unknow,ref unknow, ref unknow, ref unknow, ref unknow,ref unknow, ref unknow, ref unknow);string temp = doc.Paragraphs[1].Range.Text.Trim();Console.WriteLine("你他妈输出temp干嘛?");}catch (Exception ex){Console.WriteLine(ex.Message);}wordDoc = doc;wordDoc.Paragraphs.Last.Range.Text += "我真的不打算再写了,就写这么多吧";Console.ReadKey();}}
}

后续补充:

word文档工程变量的属性//合并单元格table.Cell(2, 2).Merge(table.Cell(2, 3));//单元格分离object Rownum = 2;object Columnnum = 2;table.Cell(2, 2).Split(ref Rownum, ref Columnnum);//单元格对齐方式WApp.Selection.Cells.VerticalAlignment =Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//插入表行table.Rows.Add(ref missing);//分页 object ib = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;WApp.Selection.InsertBreak(ref ib);//换行WApp.Selection.TypeParagraph();二、word文档设置WApp.ActiveDocument.PageSetup.LineNumbering.Active =0;//行编号WApp.ActiveDocument.PageSetup.Orientation =Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向WApp.ActiveDocument.PageSetup.TopMargin =WApp.CentimetersToPoints(float.Parse("2.54"));//上页边距WApp.ActiveDocument.PageSetup.BottomMargin = WApp.CentimetersToPoints(float.Parse("2.54"));//下页边距WApp.ActiveDocument.PageSetup.LeftMargin = WApp.CentimetersToPoints(float.Parse("3.17"));//左页边距WApp.ActiveDocument.PageSetup.RightMargin = WApp.CentimetersToPoints(float.Parse("3.17"));//右页边距WApp.ActiveDocument.PageSetup.Gutter = WApp.CentimetersToPoints(float.Parse("0"));//装订线位置WApp.ActiveDocument.PageSetup.HeaderDistance = WApp.CentimetersToPoints(float.Parse("1.5"));//页眉WApp.ActiveDocument.PageSetup.FooterDistance = WApp.CentimetersToPoints(float.Parse("1.75"));//页脚WApp.ActiveDocument.PageSetup.PageWidth = WApp.CentimetersToPoints(float.Parse("21"));//纸张宽度WApp.ActiveDocument.PageSetup.PageHeight = WApp.CentimetersToPoints(float.Parse("29.7"));//纸张高度WApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源WApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源WApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页WApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同WApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同WApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式WApp.ActiveDocument.PageSetup.SuppressEndnotes =0;//不隐藏尾注WApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距WApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印WApp.ActiveDocument.PageSetup.BookFoldPrinting =false;//不设置手动双面正面打印WApp.ActiveDocument.PageSetup.BookFoldRevPrinting =false;//不设置手动双面背面打印WApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数WApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧WApp.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量WApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格”三、光标移动//移动光标
//光标下移3行 上移3行object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;object count = 3;WApp.Selection.MoveEnd(ref unit,ref count);WApp.Selection.MoveUp(ref unit, ref count, ref missing);//Microsoft.Office.Interop.Word.WdUnits说明//wdCell                  A cell. //wdCharacter             A character. //wdCharacterFormatting   Character formatting. //wdColumn                A column. //wdItem                  The selected item. //wdLine                  A line. //行//wdParagraph             A paragraph. //wdParagraphFormatting   Paragraph formatting. //wdRow                   A row. //wdScreen                The screen dimensions. //wdSection               A section. //wdSentence              A sentence. //wdStory                 A story. //wdTable                 A table. //wdWindow                A window. //wdWord                  A word.//录制的vb宏//     ,移动光标至当前行首//    Selection.HomeKey unit:=wdLine//    '移动光标至当前行尾//    Selection.EndKey unit:=wdLine//    '选择从光标至当前行首的内容//    Selection.HomeKey unit:=wdLine, Extend:=wdExtend//    '选择从光标至当前行尾的内容//    Selection.EndKey unit:=wdLine, Extend:=wdExtend//    '选择当前行//    Selection.HomeKey unit:=wdLine//    Selection.EndKey unit:=wdLine, Extend:=wdExtend//    '移动光标至文档开始//    Selection.HomeKey unit:=wdStory//    '移动光标至文档结尾//    Selection.EndKey unit:=wdStory//    '选择从光标至文档开始的内容//    Selection.HomeKey unit:=wdStory, Extend:=wdExtend//    '选择从光标至文档结尾的内容//    Selection.EndKey unit:=wdStory, Extend:=wdExtend//    '选择文档全部内容(从WholeStory可猜出Story应是当前文档的意思)//    Selection.WholeStory//    '移动光标至当前段落的开始//    Selection.MoveUp unit:=wdParagraph//    '移动光标至当前段落的结尾//    Selection.MoveDown unit:=wdParagraph//    '选择从光标至当前段落开始的内容//    Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend//    '选择从光标至当前段落结尾的内容//    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend//    '选择光标所在段落的内容//    Selection.MoveUp unit:=wdParagraph//    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend//    '显示选择区的开始与结束的位置,注意:文档第1个字符的位置是0//    MsgBox ("第" & Selection.Start & "个字符至第" & Selection.End & "个字符")//    '删除当前行//    Selection.HomeKey unit:=wdLine//    Selection.EndKey unit:=wdLine, Extend:=wdExtend//    Selection.Delete//    '删除当前段落//    Selection.MoveUp unit:=wdParagraph//    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend//    Selection.Delete//表格的光标移动
//光标到当前光标所在表格的地单元格
WApp.Selection.Tables[1].Cell(1, 1).Select();
//unit对象定义
object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**////extend对光标移动区域进行扩展选择object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文档行方式,可以看成表格一行.不过和wdRow有区别object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,对于表格可以选择到表格行后的换车符,对于跨行合并的行选择,我能找到的最简单方式object count=1;//光标移动量
下面代码演示对于存在合并单元格的选择操作.合并单元格的选择问题一直是word的bug.部分object对象参照上面代码上面这个是表格合并样式.要如何才能选择2行标题栏尼.看下面代码//定位到表格第1单元格
WApp.Selection.Tables[1].Cell(1, 1).Select();
//定位到第1个单元格第1个字符前
WApp.Selection.HomeKey(ref unith, ref missing);
//扩展到行尾,选择表第1行
WApp.Selection.EndKey(ref unith, ref extend);
//定义表格标题的行数量,titlerow为参数
object strtitlerow=titlerow-1;
//移动光标选择第1行的末尾段落标记
WApp.Selection.MoveDown(ref unitp, ref count, ref extend);
//选择下一行,因为合并的原因,如表格标题最后列是合并,只选择了2行的部分WApp.Selection.MoveDown(ref unitu, ref strtitlerow, ref extend);
//扩展到该行的末端,保证合并行能全部选择到WApp.Selection.EndKey(ref unith, ref extend);
//复制选择内容到剪贴板WApp.Selection.Copy();
//下面是移动光标到任何位置并粘贴内容.我程序中目的是到表格换页的时候自动插入下一页的表头.WApp.Selection.Tables[1].Cell(System.Convert.ToInt32(strRownum), 1).Select();WApp.Selection.HomeKey(ref unith, ref missing);WApp.Selection.Paste();
四、段落格式设定
//段落格式设定WApp.Selection.ParagraphFormat.LeftIndent = WApp.CentimetersToPoints(float.Parse("0"));//左缩进WApp.Selection.ParagraphFormat.RightIndent = WApp.CentimetersToPoints(float.Parse("0"));//右缩进WApp.Selection.ParagraphFormat.SpaceBefore =float.Parse("0");//段前间距WApp.Selection.ParagraphFormat.SpaceBeforeAuto =0;//WApp.Selection.ParagraphFormat.SpaceAfter = float.Parse("0");//段后间距WApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//WApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距WApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端对齐WApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制WApp.Selection.ParagraphFormat.KeepWithNext = 0;//与下段同页WApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分页WApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分页WApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行号WApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字WApp.Selection.ParagraphFormat.FirstLineIndent = WApp.CentimetersToPoints(float.Parse("0"));//首行缩进WApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;WApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse("0");WApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse("0");WApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse("0");WApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse("0");WApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse("0");WApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1;WApp.Selection.ParagraphFormat.DisableLineHeightGrid =0;WApp.Selection.ParagraphFormat.FarEastLineBreakControl =1;WApp.Selection.ParagraphFormat.WordWrap = 1;WApp.Selection.ParagraphFormat.HangingPunctuation = 1;WApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0;WApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1;WApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1;WApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;五、字体格式设定
//字体格式设定WApp.Selection.Font.NameFarEast = "华文中宋";WApp.Selection.Font.NameAscii = "Times New Roman";WApp.Selection.Font.NameOther = "Times New Roman";WApp.Selection.Font.Name = "宋体";WApp.Selection.Font.Size = float.Parse("14");WApp.Selection.Font.Bold = 0;WApp.Selection.Font.Italic = 0;WApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;WApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;WApp.Selection.Font.StrikeThrough =0;//删除线WApp.Selection.Font.DoubleStrikeThrough = 0;//双删除线WApp.Selection.Font.Outline =0;//空心WApp.Selection.Font.Emboss = 0;//阳文WApp.Selection.Font.Shadow = 0;//阴影WApp.Selection.Font.Hidden = 0;//隐藏文字WApp.Selection.Font.SmallCaps = 0;//小型大写字母WApp.Selection.Font.AllCaps = 0;//全部大写字母WApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;WApp.Selection.Font.Engrave = 0;//阴文WApp.Selection.Font.Superscript = 0;//上标WApp.Selection.Font.Subscript = 0;//下标WApp.Selection.Font.Spacing = float.Parse("0");//字符间距WApp.Selection.Font.Scaling = 100;//字符缩放WApp.Selection.Font.Position = 0;//位置WApp.Selection.Font.Kerning = float.Parse("1");//字体间距调整WApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果WApp.Selection.Font.DisableCharacterSpaceGrid =false;WApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;六、终于找到了获取光标位置的东东。那里找到的忘了,感谢提供的老大。放到这里供大家参考。
有了这个和上面内容,相信大家对word文档的控制应该到了随心所欲的地步,爽啊
获取的c#语法 //get_Information
Selection.get_Information(WdInformation.wdActiveEndPageNumber)
//关于行号-页号-列号-位置//information 属性 //返回有关指定的所选内容或区域的信息。variant 类型,只读。 //expression.information(type) //expression 必需。该表达式返回一个 range 或 selection 对象。 //type long 类型,必需。需要返回的信息。可取下列 wdinformation 常量之一: //wdactiveendadjustedpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾。如果设置了一个起始页码,并对页码进行了手工调整,则返回调整过的页码。 //wdactiveendpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾,页码从文档的开头开始计算而不考虑对页码的任何手工调整。 //wdactiveendsectionnumber 返回节号,在该节中包含了指定的所选内容或区域的活动结尾。 //wdatendofrowmarker 如果指定的所选内容或区域位于表格的行结尾标记处,则本参数返回 true。 //wdcapslock 如果大写字母锁定模式有效,则本参数返回 true。 //wdendofrangecolumnnumber 返回表格列号,在该表格列中包含了指定的所选内容或区域的活动结尾。 //wdendofrangerownumber 返回表格行号,在该表格行包含了指定的所选内容或区域的活动结尾。 //wdfirstcharactercolumnnumber 返回指定的所选内容或区域中第一个字符的位置。如果所选内容或区域是折叠的,则返回所选内容或区域右侧紧接着的字符编号。 //wdfirstcharacterlinenumber 返回所选内容中第一个字符的行号。如果 pagination 属性为 false,或 draft 属性为 true,则返回 - 1。 //wdframeisselected 如果所选内容或区域是一个完整的图文框文本框,则本参数返回 true。 //wdheaderfootertype 返回一个值,该值表明包含了指定的所选内容或区域的页眉或页脚的类型,如下表所示。 值 页眉或页脚的类型 //- 1 无 //0 偶数页页眉 //1 奇数页页眉 //2 偶数页页脚 //3 奇数页页脚 //4 第一个页眉 //5 第一个页脚 //wdhorizontalpositionrelativetopage 返回指定的所选内容或区域的水平位置。该位置是所选内容或区域的左边与页面的左边之间的距离,以磅为单位。如果所选内容或区域不可见,则返回 - 1。 //wdhorizontalpositionrelativetotextboundary 返回指定的所选内容或区域相对于周围最近的正文边界的左边的水平位置,以磅为单位。如果所选内容或区域没有显示在当前屏幕,则本参数返回 - 1。 //wdinclipboard 有关此常量的详细内容,请参阅 microsoft office 98 macintosh 版的语言参考帮助。 //wdincommentpane 如果指定的所选内容或区域位于批注窗格,则返回 true。 //wdinendnote 如果指定的所选内容或区域位于页面视图的尾注区内,或者位于普通视图的尾注窗格中,则本参数返回 true。 //wdinfootnote 如果指定的所选内容或区域位于页面视图的脚注区内,或者位于普通视图的脚注窗格中,则本参数返回 true。 //wdinfootnoteendnotepane 如果指定的所选内容或区域位于页面视图的脚注或尾注区内,或者位于普通视图的脚注或尾注窗格中,则本参数返回 true。详细内容,请参阅前面的 wdinfootnote 和 wdinendnote 的说明。 //wdinheaderfooter 如果指定的所选内容或区域位于页眉或页脚窗格中,或者位于页面视图的页眉或页脚中,则本参数返回 true。 //wdinmasterdocument 如果指定的所选内容或区域位于主控文档中,则本参数返回 true。 //wdinwordmail 返回一个值,该值表明了所选内容或区域的的位置,如下表所示。值 位置 //0 所选内容或区域不在一条电子邮件消息中。 //1 所选内容或区域位于正在发送的电子邮件中。 //2 所选内容或区域位于正在阅读的电子邮件中。 //wdmaximumnumberofcolumns 返回所选内容或区域中任何行的最大表格列数。 //wdmaximumnumberofrows 返回指定的所选内容或区域中表格的最大行数。 //wdnumberofpagesindocument 返回与所选内容或区域相关联的文档的页数。 //wdnumlock 如果 num lock 有效,则本参数返回 true。 //wdovertype 如果改写模式有效,则本参数返回 true。可用 overtype 属性改变改写模式的状态。 //wdreferenceoftype 返回一个值,该值表明所选内容相对于脚注、尾注或批注引用的位置,如下表所示。 值 描述 //— 1 所选内容或区域包含、但不只限定于脚注、尾注或批注引用中。 //0 所选内容或区域不在脚注、尾注或批注引用之前。 //1 所选内容或区域位于脚注引用之前。 //2 所选内容或区域位于尾注引用之前。 //3 所选内容或区域位于批注引用之前。 //wdrevisionmarking 如果修订功能处于活动状态,则本参数返回 true。 //wdselectionmode 返回一个值,该值表明当前的选定模式,如下表所示。 值 选定模式 //0 常规选定 //1 扩展选定 //2 列选定 //wdstartofrangecolumnnumber 返回所选内容或区域的起点所在的表格的列号。 //wdstartofrangerownumber 返回所选内容或区域的起点所在的表格的行号。 //wdverticalpositionrelativetopage 返回所选内容或区域的垂直位置,即所选内容的上边与页面的上边之间的距离,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。 //wdverticalpositionrelativetotextboundary 返回所选内容或区域相对于周围最近的正文边界的上边的垂直位置,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。 //wdwithintable 如果所选内容位于一个表格中,则本参数返回 true。 //wdzoompercentage 返回由 percentage 属性设置的当前的放大百分比。

C#与Word的操作--转载相关推荐

  1. .net 使用 Aspose.Words 进行 Word替换操作

    .net 使用 Aspose.Words 进行 Word替换操作 原文 http://www.cnblogs.com/codealone/archive/2013/04/02/2995224.html ...

  2. Word实用操作技巧之文字编辑(转)

    Word实用操作技巧之文字编辑(转) 为了发挥Word 的强大功能,建议你在使用时试试以下的技巧,灵活运用这些技巧,可以使你迅速成为Word高手(这里我们以Word XP为例,其他版本请参考操作). ...

  3. 计算机硬件Word,[计算机硬件及网络]word的操作.doc

    [计算机硬件及网络]word的操作.doc Office Word 2010高级应用技术长文档排版一.考查知识点内置样式修改与使用.新建样式.题注.交叉引用.脚注与尾注.目录.图表目录.分节符的使用. ...

  4. python怎么重命名word文件,Python读取word文本操作详解

    本文研究的主要问题时Python读取word文本操作,分享了相关概念和实现代码,具体如下. 一,docx模块 Python可以利用python-docx模块处理word文档,处理方式是面向对象的.也就 ...

  5. 计算机应用操作题word,计算机应用基础网考模拟练习题Word部分操作题

    计算机应用基础网考模拟练习题Word部分操作题 1.打开当前试题目录中的TEST1.DOC文件,并完成下面操作: (1)在" 基于Windows95/98"后添加"操作系 ...

  6. office是python打开方式_Python读取word文本操作详解

    本文研究的主要问题时Python读取word文本操作,分享了相关概念和实现代码,具体如下. 一,docx模块 Python可以利用python-docx模块处理word文档,处理方式是面向对象的.也就 ...

  7. WPS怎么在线转换成Word,WPS转换成Word的操作步骤

    WPS转换成Word怎么操作?WPS文件也会比较熟悉的办公软件,但是WPS和Word的操作方法也有不一样的地方,所以将WPS转换成Word就是为了更好的操作文档,接下来就一起看一下WPS转换成Word ...

  8. 计算机word基础操作知识

    计算机word基础操作知识点 1. Word 2003的基本功能有:(1)文字的编辑和自动更正:(2)格式的编排和文档的打印:(3)表格的制作:(4)图形和图像的设置:(5)链接与嵌入:(6)帮助功能 ...

  9. 怎么把word里面的彩色图转化为灰度图,直接在word里面操作,无需转其他软件,超简单!(位图和矢量图都可以)

    怎么把word里面的彩色图转化为灰度图,直接在word里面操作,无需转其他软件,超简单!(位图和矢量图都可以) Microsoft Office Word是微软公司的一个文字处理器应用程序.它最初是由 ...

最新文章

  1. pytorch实现手写数字识别_Paddle和Pytorch实现MNIST手写数字集识别对比
  2. 【笨木头Lua专栏】基础补充08:协同程序之resume-yield间的数据返回
  3. 自然语言处理中的模式(模式1.概率化模式)
  4. PHP base64
  5. Android之解决Gigaset手机不能设置DeviceOwner权限提示already provisioned问题
  6. USACO 6.3 章节 你对搜索和剪枝一无所知QAQ
  7. BZOJ 1016: [JSOI2008]最小生成树计数( kruskal + dfs )
  8. python opencv人脸解锁_教你使用python+Opencv完成人脸解锁
  9. 【图像去雾】基于matlab GUI直方图均衡化+Retinex理论图像去雾(带面板)【含Matlab源码 706期】
  10. 全球名校AI课程库(36)| 辛辛那提大学 · 离散数学课程『MATH1071 Discrete Math』
  11. 如何成为一个优秀的计算机工程师,如何成为一个优秀的电气工程师
  12. linux关闭防火墙时出现问号乱码,linux文件名乱码问题的解决方...-tcp_wrappers防火墙配置方法-su 与 su - 的比较_169IT.COM...
  13. dp题目总结(1)——基础
  14. 双鱼林 android 服务器,双鱼林安卓Android代码生成器下载_双鱼林安卓Android代码生成器官方下载-太平洋下载中心...
  15. 美元对全球汇率 免费 api
  16. 【错解】【附正解】“科林明伦杯”哈尔滨理工大学第十届程序设计竞赛 - E 赛马
  17. Android10.0 展讯平台解锁
  18. DataStage记录
  19. 博士申请 | 美国加州大学圣克鲁兹分校王鑫教授招收NLP/CV方向全奖博士生
  20. java调用office接口_java调用com组件操作word使用总结(jacob)

热门文章

  1. 小红书是如何赚到翻车的?
  2. 解决Godaddy付款时的There was a problem processing your transaction. Please verify your payment information
  3. linux下vhd win10,VHD双系统(windows10)
  4. js小白之路(八)——正则表达式
  5. web of science怎么登陆_10 种最流行的 Web 挖掘工具 | 程序员硬核评测
  6. Linux CentOS 7 系统安装Redis集群
  7. 隐藏iframe滚动条
  8. 学术前沿趋势分析1:论文数据统计
  9. linux笔记本无法识别显示器,为了解决笔记本外接显示器导致Ubuntu显示异常的问题,我做了这么多事情......
  10. LaTex一行排列多个图,并且加入每个图都添加小标题