C#生成Word文档

来源:互联网 发布:mac 预览 目录 编辑:程序博客网 时间:2024/04/27 23:44
 

I.     环境:

VS2005 SP1office 2003

II. 设置:

首先在工程中添加ReferenceMicrosoft Word 11.0 Object Library。同时在cs文件开头using word

III.         代码:

A.   初始:

1.       设定文档名称

Object FileName = 示例;

2.       创建两个object

Object Nothing = System.Reflection.Missing.Value;

Object EndOfDoc = "//endofdoc";

3.       创建word文档

Word.ApplicationWordApp = new Word.ApplicationClass();

              Word.Paragraph ParaHeader;

Word.DocumentWordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, refNothing, ref Nothing);

B.   写入内容:

1.      添加一段文字:

ParaHeader =WordDoc.Content.Paragraphs.Add(ref Nothing);

              ParaHeader.Range.Text ="一段文字";

              ParaHeader.Alignment =Word.WdParagraphAlignment.wdAlignParagraphCenter;

              ParaHeader.Range.Font.Bold= 3;

              ParaHeader.Range.Font.Size= 26;

              ParaHeader.Range.Font.Name= "宋体";

ParaHeader.Range.InsertParagraphAfter();

 

各句含义可从其属性名称中得知。

2.       换行:

object count = 35;

              object WdLine = Word.WdUnits.wdLine;

              WordApp.Selection.MoveDown(ref WdLine, refcount, ref Nothing);

              WordApp.Selection.TypeParagraph();

WordApp.Selection.ParagraphFormat.Alignment= WdParagraphAlignment.wdAlignParagraphLeft;

 

各句含义可从其属性名称中得知。

3.      添加图片:

String PicPathWeek = System.Windows.Forms.Application.StartupPath + "//Week.gif";

WordApp.Selection.InlineShapes.AddPicture(PicPathWeek,ref Nothing, refNothing, ref Nothing);

 

各句含义可从其属性名称中得知

C.    文件保存:

WordDoc.SaveAs(refFileName, ref Nothing, refNothing, ref Nothing, refNothing, ref Nothing, refNothing, ref Nothing, refNothing, ref Nothing, refNothing, ref Nothing, refNothing, ref Nothing, refNothing, ref Nothing);

         WordDoc.Close(ref Nothing, refNothing, ref Nothing);

          WordApp.Quit(ref Nothing, refNothing, ref Nothing);

原创粉丝点击