C#调用WORDApp
来源:互联网 发布:幼儿园美工课 编辑:程序博客网 时间:2024/05/05 04:11
原文地址:http://www.codeproject.com/KB/cs/winwordloader.aspx
原文内容:
Introduction
In applications I develop, I often use Microsoft Word to generate various documents (reports, agendas, invoices, etc). The code to load and shut down the WinWord's COM server was always the same, so I wrote a simple helper class which manages this.
The Code
using System;using System.Threading;using System.Runtime.InteropServices;namespace AlexKay.Office{ /// <summary> /// Helper class to manage the Word.Application coclass. /// </summary> public class WordLoader : IDisposable { private Word.Application wordApp = null; private bool isNewApp = false; private bool disposed = false; public WordLoader() { // Check if Word is registered in the ROT. try { wordApp = (Word.Application)Marshal. GetActiveObject("Word.Application"); } catch { wordApp = null; } // Load Word if it's not. if(wordApp == null) { try { wordApp = new Word.ApplicationClass(); isNewApp = true; } catch { wordApp = null; } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { // Dispose managed resources. } // Dispose unmanaged resources. if(wordApp != null) { try { if(isNewApp && wordApp.Documents.Count == 0) { object arg1 = Word.WdSaveOptions. wdDoNotSaveChanges; object arg2 = null; object arg3 = null; wordApp.Quit(ref arg1, ref arg2, ref arg3); // Wait until Word shuts down. for(;;) { Thread.Sleep(100); try { // When word shuts down this call // throws an exception. string dummy = wordApp.Version; } catch { break; } } } } catch {} wordApp = null; } } disposed = true; } ~WordLoader() { Dispose(false); } public Word.Application Application { get { return wordApp; } } }}
Comments
When the WordLoader
object is created, it checks if the Word
co-class is already created and registered in the running object table. If it's not, it creates a new instance of the Word.Application
co-class which loads the WinWord application. When the WordLoader
object is disposed it shuts down Word, if it has no documents open.
As you can see, this is quite simple. Any comments on the code are welcome!
- C#调用WORDApp
- C#调用JavaScript JavaScript调用C#
- C#调用js && js调用C#事件
- Unity JavaScript调用C# C#调用JavaScript
- c# 调用c++ && c++调用c# 函数
- C#异步调用
- C#调用DLL方法
- C#调用API
- C#中调用API
- C#调用API
- C#调用API
- C#中调用API
- C#调用windows API
- C#中调用API
- C#中调用Javascript
- C#中调用API
- C#动态方法调用
- c#中调用DTS
- Office Word 开发常用网址
- 企业流程管理解决方案
- 软件园里的流氓(7)
- 外接共享插件和VSTO 2005 SE 插件的对比
- The second generation: Intel's EPT and AMD's NPT
- C#调用WORDApp
- Flash 调用WebService
- [37周]
- 图片旋转效果
- vb 对 zebra 888-TT打印机编程
- 视频
- Converting an RGB image to 1 bit-per-pixel monochrome(源码)
- MMU分析
- 定义JavaScript中的StringBuffer类