I. 环境:
VS2005 SP1,office 2003
II. 设置:
首先在工程中添加Reference:Microsoft 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.Application WordApp = new Word.ApplicationClass();
Word.Paragraph ParaHeader;
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, 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, ref count, 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, ref Nothing, ref Nothing);
各句含义可从其属性名称中得知
C. 文件保存:
WordDoc.SaveAs(ref FileName, 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);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);