1) 首先添加"COM“引用
打开"添加引用"对话框,选中"COM"选项,添加名为"Microsoft Word 11.0 Object Library"的引用。成功添加后,在"References"中多出了三个引用,分别为"Microsoft.Office..Core" 、"VBIDE"和"Word".
2)编写代码
/*
* 文件名:WriteToWordDemo.cs
* 说明:创建Word文档,并写入内容
* 时间:2008-9-20
* 开发环境:Visual studio 2008
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
namespace WriteToWordDemo
{
class WriteToWordDemo
{
static void Main(string[] args)
{
object path; // 文件路径
string content; // 写入文件的内容
Application wordApp; // word应用程序对象
Document wordDoc; // word文档对象
path = "c://myWord.doc";
wordApp = new Application();
if (File.Exists((string)path)) // 如果文件存在,则删除
{
File.Delete((string)path);
}
object nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);
content = "Write content to word document.";
wordDoc.Paragraphs.Last.Range.Text = content; // 写入内容
object format = WdSaveFormat.wdFormatDocument; // word文档保存格式
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.Close(ref nothing, ref nothing, ref nothing); // 关闭word文档对象
wordApp.Quit(ref nothing, ref nothing, ref nothing); // 关闭word应用程序对象
Console.WriteLine("over.");
}
}
}