转自博客:
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;
- //用richTextBox打开带格式的word文档。
- //先打开word文档,全选其中的内容并保存的剪切板中,最后在richTextBox中粘贴数据,并关闭文档,支持图片和文字格式显示
- 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();//全选word文档中的数据
- doc.ActiveWindow.Selection.Copy();//复制数据到剪切板
- richTextBox1.Paste();//richTextBox粘贴数据
- //richTextBox1.Text = doc.Content.Text;//显示无格式数据
- }
- 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);//复制RTF数据到剪贴板
- 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;
- }
- }
- }