2024年2月7日发(作者:)

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

1.1. VSTO

VSTO,就是Visual Studio Tools for the Microsoft Office System。可以在这里找到更多信息:

/office/understanding/vsto/

首先,必须在系统中安装VSTO。(不用安装Office即可使用)

为了使用VSTO,我们的工程需要引入如下引用:

图1-1 引用示范

其中指的是“”,你可以通过下面的图样了解如何添加这个COM引用:

图1-2 添加Word引用

其中指的是“Microsoft Office 11.0 Object Library”,你可以通过下面的图样了解如何添加这个COM引用:

图1-3 添加引用

1.2. ationClass打开文档

用Word打开指定的文档很简单。

代码

// a reference to Word application

private ationClass m_oWordApp =

new ationClass();

// a reference to the document

private nt m_oDoc;

object fileName = strDocumentFilePath;

m_e = false;

m_oDoc =

m_(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_te();

/// /library/wt26ady8(en-us,vs.80).aspx

/// convert all list numbers and LISTNUM fields in the document to text

object numberType =

erAllNumbers;

m_tNumbersToText(ref numberType);

激活。

记得调用te()将当前打开的文档ConvertNumbersToText方法是用来把文档中所有的编号符号转换为文本的。

1.3. 选定文档范围

还有这个接口,可以选定某一段文字,按照指定的方式复制出来。

代码

object rangeStart = begin;

object rangeEnd = (end < nCount)?end:nCount;

rng =

m_(ref rangeStart, ref rangeEnd);

();

/////////////////////////////////////////////////////

///

trievalMode RetrievalMode =

trievalMode;

eHiddenText = false;

eFieldCodes = false;

/// sets the view for text retrieval to Web view

pe =

iew;

///

/////////////////////////////////////////////////////

String strYourWord = ;

1.4. 销毁一切

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

代码

/// 关闭打开的文档:

if(m_oDoc != null)

{

}

if(m_oWordApp != null)

{

// 否则会出现“eption

// 这里就不要再判断if(m_Document != null)m_(ref saveChanges, ref missing, ref missing);

m_oDoc = null;

(0x800A1098): 因为没有打开的文档,所以这一命令无效。”

// 这样的异常!

m_(ref saveChanges, ref missing, ref missing);

m_oWordApp = null;

}