[C#]利用VSTO操作Office文档而无需安装Office

来源:互联网 发布:网络视频录下来 编辑:程序博客网 时间:2024/05/16 07:12
1.1. VSTO
   VSTO,就是Visual Studio Tools for the Microsoft Office System。可以在这里找到更多信息:
       http://msdn.microsoft.com/office/understanding/vsto/default.aspx
首先,必须在系统中安装VSTO(不用安装Office即可使用)
       为了使用VSTO,我们的工程需要引入如下引用:
       其中指的是“Microsoft.Office.Interop.Word”,你可以通过下面的图样了解如何添加这个COM引用:
其中指的是“Microsoft Office 11.0 Object Library”,你可以通过下面的图样了解如何添加这个COM引用:
 
1.2. Word.ApplicationClass打开文档
   用Word打开指定的文档很简单。

代码
// a reference to Word application
private Microsoft.Office.Interop.Word.ApplicationClass m_oWordApp =
new Microsoft.Office.Interop.Word.ApplicationClass();
// a reference to the document
private Microsoft.Office.Interop.Word.Document m_oDoc;
 
object fileName = strDocumentFilePath;             
 
m_oWordApp.Visible = false;
 
m_oDoc =
    m_oWordApp.Documents.Open(ref fileName, 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);
 
m_oDoc.Activate();
 
/// http://msdn2.microsoft.com/library/wt26ady8(en-us,vs.80).aspx
/// convert all list numbers and LISTNUM fields in the document to text
object numberType =
    Microsoft.Office.Interop.Word.WdNumberType.wdNumberAllNumbers;
m_oDoc.ConvertNumbersToText(ref numberType);

       记得调用Microsoft.Office.Interop.Word.Document.Activate()将当前打开的文档激活。
ConvertNumbersToText方法是用来把文档中所有的编号符号转换为文本的。
1.3. Word.Range选定文档范围
   还有Word.Range这个接口,可以选定某一段文字,按照指定的方式复制出来。

代码
object rangeStart = begin;
object rangeEnd = (end < nCount)?end:nCount;
Microsoft.Office.Interop.Word.Range rng =
    m_oDoc.Range(ref rangeStart, ref rangeEnd);
rng.Select();
 
/////////////////////////////////////////////////////
///
Microsoft.Office.Interop.Word.TextRetrievalMode RetrievalMode =
    rng.FormattedText.TextRetrievalMode;
RetrievalMode.IncludeHiddenText = false;
RetrievalMode.IncludeFieldCodes = false;
/// sets the view for text retrieval to Web view
RetrievalMode.ViewType =
    Microsoft.Office.Interop.Word.WdViewType.wdWebView;
///
/////////////////////////////////////////////////////
 
String strYourWord = rng.FormattedText.Text;

  
1.4. 销毁一切
   无论发生了什么事情,都必须保证WinWord.exe实例被释放,这是一个服务的基本要求。

代码
///关闭打开的文档:
if(m_oDoc != null)
{
    m_oDoc.Close(ref saveChanges, ref missing, ref missing);
    m_oDoc = null;
}
if(m_oWordApp != null)
{
    // 这里就不要再判断if(m_oWordApp.Application.ActiveDocument != null)了
    // 否则会出现“System.Runtime.InteropServices.COMException (0x800A1098): 因为没有打开的文档,所以这一命令无效。”
    // 这样的异常!
    m_oWordApp.Application.Quit(ref saveChanges, ref missing, ref missing);
   
    m_oWordApp = null;
}

 
原创粉丝点击