转自博客:
http://blog.csdn.net/michellehsiao/article/details/7684309
小知识点:.Net Framework 4.0 和.Net Framework 4.0 Client Profile区别:
.NET Framework Client Profile是.NET Framework的裁剪版本。它面向客户端应用程序。它提供 Windows Presentation Foundation (WPF)、Windows 窗体、Windows Communication Foundation (WCF)和 ClickOnce 功能的简化子集。这可以为面向.NET Framework Client Profile 的 WPF、Windows 窗体、WCF 和控制台应用程序实现快速部署方案。
主要内容:
当在 Visual Studio 2010 建立新项目时,如果发现 [添加引用] 中没有列出原本应该列出的组件时,可以先检查是否是项目的目标框架是否设成了 .NET 4.0 Client Profile (例如 System.Web.dll 就不在 .NET 4.0 Client Profile 套件中)。
1、添加引用:COM组件下的Microsoft Word 11.0 Object Library ,然后会出现Microsoft Office Core和Word以及VBIDE的引用,如下图
2、修改项目属性嵌入互操作类型为false,
3、接着在命名空间中写入如下内容:
这样就可以顺利使用下面代码,而不会出错!
Word.ApplicationClass app = new Word.ApplicationClass();
Word.Document doc = null;
-
-
-
public void OpenWord(string fileName)
-
{
-
Word.ApplicationClass app = new Word.ApplicationClass();
-
Word.Document doc = null;
-
object missing = System.Reflection.Missing.Value;
-
object File = fileName;
-
object readOnly = false;
-
object isVisible = true;
-
try
-
{
-
doc = app.Documents.Open(ref File, ref missing, ref readOnly,
-
ref missing, ref missing, ref missing, ref missing, ref missing,
-
ref missing, ref missing, ref missing, ref isVisible, ref missing,
-
ref missing, ref missing, ref missing);
-
-
doc.ActiveWindow.Selection.WholeStory();
-
doc.ActiveWindow.Selection.Copy();
-
richTextBox1.Paste();
-
-
}
-
finally
-
{
-
if (doc != null)
-
{
-
doc.Close(ref missing, ref missing, ref missing);
-
doc = null;
-
}
-
-
if (app != null)
-
{
-
app.Quit(ref missing, ref missing, ref missing);
-
app = null;
-
}
-
}
-
}
修改RichTextBox内容后,另存为功能实现代码如下:
-
public void SaveAsWord(string fileName)
-
{
-
Word.ApplicationClass app = new Word.ApplicationClass();
-
Word.Document doc = null;
-
object missing = System.Reflection.Missing.Value;
-
object File = fileName;
-
try
-
{
-
doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
-
-
doc.ActiveWindow.Selection.WholeStory();
-
richTextBox1.SelectAll();
-
Clipboard.SetData(DataFormats.Rtf, richTextBox1.SelectedRtf);
-
doc.ActiveWindow.Selection.Paste();
-
-
doc.SaveAs(ref File, ref missing, ref missing,
-
ref missing, ref missing, ref missing,
-
ref missing, ref missing, ref missing,
-
ref missing, ref missing, ref missing,
-
ref missing, ref missing, ref missing,
-
ref missing);
-
}
-
finally
-
{
-
if (doc != null)
-
{
-
doc.Close(ref missing, ref missing, ref missing);
-
doc = null;
-
}
-
-
if (app != null)
-
{
-
app.Quit(ref missing, ref missing, ref missing);
-
app = null;
-
}
-
}
-
}