简体   繁体   English

如何在C#中使用CreateObject打开Word文档?

[英]How can I open a word document by using CreateObject in C#?

I tried it by using the following code,but it threw an exception. 我通过使用以下代码进行了尝试,但它引发了异常。 "Exception has been thrown by the target of an invocation."

System.Type wordType = System.Type.GetTypeFromProgID("Word.Application");
        Object word = System.Activator.CreateInstance(wordType);
        wordType.InvokeMember("Visible", BindingFlags.SetProperty, null, word, new Object[] { true });
        Object documents = wordType.InvokeMember("Documents", BindingFlags.GetProperty, null, word, null);
        object nullobj = Missing.Value;
        string fileName=System.AppDomain.CurrentDomain.BaseDirectory + "assets\\sample_doc.docx";
        object[] args = new object[15] { fileName, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj};
        Object document = documents.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, documents,args);`
using (FileStream stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
 Document Doc = new Document(stream);
}
public void openWordDocument(string filePath)
{
    object missing = System.Reflection.Missing.Value;

    //create a document in this path  
    object fileName = filePath;

    object wordApp = Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"));
    //Setup our Word.Document  
    object wordDoc = wordApp.GetType().InvokeMember("Documents", System.Reflection.BindingFlags.GetProperty, null, wordApp, null);
    //Set Word to be not visible  
    wordApp.GetType().InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, wordApp, new object[] { true });

    //Open the word document fileName  
    object activeDoc = wordDoc.GetType().InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, wordDoc, new Object[] { fileName });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM