比较全的一个C#操作word文档示例

 更新时间:2020年6月25日 11:29  点击:1618

最近两天研究了一下如何使用VS2008(C#语言)输出Word文档。以下是几点总结:

1、非常简单。

2、开发及运行环境要求。操作系统为:WindowsXP(安装.net framework2.0)/Vista/Win7;在操作系统必须安装Word2003完全安装版。这里必须要强调是Word2003完全安装版,因为软件开发及运行都需要一个com组件:Microsoft word 11.0 Object Library。如果不是Word2003完全安装版,可以下载这个com组件,并手动的安装这个com组件。下载地址为:http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20923,文件不大,只有4M左右。

3、C#工程设置。这里的工程设置,就是添加com组件。步骤为:在工程资源管理器中"添加引用"->"com"选项卡->在下拉列表中选Microsoft word 11.0 Object Library。ok了,看上去,跟添加一般的dll一样,但实际上vs2008在这个过程中完成一系列复杂的关于.net调用com组件的操作,不过,幸好我们不用管这个。

4、接下就是写代码了。在这里,使用Word的com对像,跟使用一般的非com对像一样,非常流畅,好像根本就不管它什么com不com的。为了使代码比较简洁,可以在源代码文件顶添加这样的一条语句:using Word = Microsoft.Office.Interop.Word;

5、最好是对word对像模型有一定的了解,这样在写代码的时候就不会那么“迷茫”了。wore对像模型中有几个比较重要的对像,它们是Application、Document、Selection、Range、Bookmark,以及其它的一些对像,如:Paragraph、Section、Table等级。刚开始学的时候,感觉Selection、Range、Bookmark这几个对像有点迷惑人,Selection可能好理解,就是表示当前的选择区域,如果没有选择就表示光标所在位置。Range和Bookmark,其实在很多地方很像,不过也有一些区别,在这里就不多说了,google一下"word.Range"就行了。

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

7、以下给出一个示例,这个示例里面包括了一些常用的图、文、表、公式的编辑与排版以及页面设置、页眉、页码的操作,里面都有注释,写得很清楚。

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);
    }
   
  }

}

[!--infotagslink--]

相关文章

  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • php svn操作类

    以前我们开发大型项目时都会用到svn来同步,因为开发产品的人过多,所以我们会利用软件来管理,今天发有一居然可以利用php来管理svn哦,好了看看吧。 代码如下 ...2016-11-25
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • C#绘制曲线图的方法

    这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • 经典实例讲解C#递归算法

    这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25