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

1.1. VSTO
   VSTO ,就是 Visual Studio Tools for the Microsoft Office System 。可以在这里找到更多信息:
首先,必须在系统中安装 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;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值