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

时间:2012-11-12 06:33:29

标签: c# ms-word

我使用以下代码尝试了它,但它引发了异常。"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);`

2 个答案:

答案 0 :(得分:1)

using (FileStream stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
 Document Doc = new Document(stream);
}

答案 1 :(得分:0)

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 });
}