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

创建Word;

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

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

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

设置页眉、页码;

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

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

保存Word,打印Word;

重新打开Word等。

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

准备工作:

/*
1. 添加引用COM里面的 Microsoft Word 12.0 Object. Library 引用(12.0表示Word 2007版本)2. 导命名空间using MSWord =Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;3. 把引用中的Microsoft.Office.Interop.Word的“属性”中的嵌入互操作设为False
*/

以下是全部代码:(代码有点长,但请不要有压力,直接复制进去就能直接成功运行)

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内容如下图所示:

参考资料:

http://blog.csdn.net/ruby97/article/details/7406806

http://blog.csdn.net/yhrun/article/details/7674540

http://www.cnblogs.com/eye-like/p/4121219.html

http://www.cnblogs.com/knowledgesea/archive/2013/05/24/3095376.html

http://www.cnblogs.com/shi2172843/p/5848116.html

https://msdn.microsoft.com/en-us/library/bb257531(v=office.12).aspx

http://wenku.baidu.com/view/80ec0a6c1eb91a37f1115cab.html?from=search

原文链接:https://www.cnblogs.com/yxhblog/p/7084013.html

C#操作Word的方法总结相关推荐

  1. python在windows下操作word的方法的代码

    把写内容过程经常用的一些内容收藏起来,下边内容内容是关于python在windows下操作word的方法的内容,希望能对各位朋友有些好处. import win32com from win32com. ...

  2. word python 域 操作_python实现在windows下操作word的方法

    本文实例讲述了python实现在windows下操作word的方法.分享给大家供大家参考.具体实现方法如下: import win32com from win32com.client import D ...

  3. java 操作office_Java操作word的方法

    使用Java操作word的方法有几个,我一一列出来:IText,Apache的POI包,tm-extractors包,jacob包,java2word包. IText包比较大,但是功能比较全.而且比较 ...

  4. python可以操作word吗_python实现在windows下操作word的方法

    import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.A ...

  5. python写word下标_python实现在windows下操作word的方法

    import win32com from win32com.client import Dispatch, constants w = win32com.client.Dispatch('Word.A ...

  6. python读取word的方法,Python读取Word(.docx)正文信息的方法

    Python读取Word(.docx)正文信息的方法 本文介绍用Python简单读取*.docx文件信息,一些python-word库就是对这种方法的扩展. 介绍分两部分: Word(*.docx)文 ...

  7. Word进行自动生成目录右边页面等格操作简单详细方法

    Word进行自动生成目录右边页面等格操作简单详细方法 Word文档自动生成的目录,但是由于目录的右边不等(见下图),看起来不美观,所以我们可以将目录右边页面进行等格处理. 方法步骤如下: 一.首先选择 ...

  8. Excel 操作 Word 常用属性和方法

    一.新建Word引用 需要首先创建一个对 Word Application 对象的引用.在VBA中,工具-引用,选取"MicroSoft Word 11.0 Object Library&q ...

  9. php com操作word,PHP操作word方法(读取和写入)

    PHP操作word方法(读取和写入) 发布于 2014-07-21 22:52:41 | 131 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: Hypertext ...

最新文章

  1. python连接服务器代码_python服务器端收发请求的实现代码
  2. java中布尔值做比较_Java中的三态布尔值
  3. Python应用实战-在pandas中利用hdf5高效存储数据
  4. 2019.8.2闭包,作用域
  5. Hadoop集群搭建过程中ssh免密码登录(二)
  6. 【服务器】【个人网盘】宝塔搭建cloudreve
  7. php mysql难不难_PHP操作mysql数据库
  8. OpenCV(图像处理)—访问像素的三种方法
  9. Mobile Widget——让开发移动应用就像做网页
  10. 01数据结构——绪论
  11. Mariadb 安装 启动 及错误 1067 问题解决
  12. 随机过采样与随机欠采样 代码
  13. android创建桌面快捷方式
  14. 【图床】PicGo配置图片压缩
  15. 关于调用360极速浏览器 2345浏览器的方法
  16. 笔记本不能用无线网策略服务器,明明有无线网笔记本就是搜索不到怎么处理
  17. 艾宾浩斯遗忘曲线复习计划表
  18. Java职责链模式详解
  19. 诺基亚7原生android,诺基亚7快速上手体验:蔡司镜头回归,原生Android味
  20. 网站安全防护该怎么做?有什么具体措施?

热门文章

  1. C/C++ 实现屏幕绘制字体
  2. 华为云会议初体验【华为云至简致远】
  3. ASP PHP和JSP三大动态网页技术
  4. 黑客组织 Lizard Squad 承认黑了联想官网
  5. 华为无线设备安全策略配置命令
  6. 【C语言】之实现 printf 函数功能
  7. 5.20福利提前送,视频+直播免费领取。
  8. flutter 支付宝支付
  9. 以最美的名义 大连京东物流小哥登上2018央视新春舞台
  10. SRGAN 图像超分辨率重建(Keras)