Wednesday, September 28, 2011

Open word document using interop.word


Microsoft.Office.Interop.Word.ApplicationClass oWord1;
    Microsoft.Office.Interop.Word.Document oDoc1;
    object objFalse = false;
    object objTrue = true;
    object missing = System.Reflection.Missing.Value;
    Microsoft.Office.Interop.Word.Find fnd;
    Microsoft.Office.Interop.Word.Range rngdoc;

/// <summary>
    /// Open word document
    /// </summary>
    public string OpenDocument()
    {

        if (oWord1 != null && oDoc1 != null)
        {
            oDoc1.Close(ref objTrue, ref missing, ref missing);
            oWord1.Quit(ref objTrue, ref missing, ref missing);
            while (Marshal.ReleaseComObject(oDoc1) != 0)
            { }
            while (Marshal.ReleaseComObject(oWord1) != 0)
            { }
            oDoc1 = null;
            oWord1 = null;
        }

        if (oWord1 == null && oDoc1 == null)
        {
            //If word object is nul then create objects for accessing the wod document
            createObjects();
        }
        if (!Directory.Exists(Server.MapPath("~/Temp/")))
        {
            Directory.CreateDirectory(Server.MapPath("~/Temp/"));
        }
        object sFileName = Server.MapPath(strWordDocumentPath);
        oDoc1 = oWord1.Documents.Open(ref sFileName, ref objFalse, ref objFalse,
                     ref objFalse, ref missing, ref missing, ref missing, ref missing,
                     ref missing, ref missing, ref missing,
                     ref objTrue, ref missing, ref missing, ref missing);
        oDoc1.Activate();
        System.Object start = 0;
        System.Object end = oDoc1.Characters.Count;
        rngdoc = oDoc1.Range(ref start, ref end);



        string txtwordcontents = rngdoc.Text;
        txtPDFText.Text += txtwordcontents;
        return txtwordcontents;
    }

    /// <summary>
    /// this method is used to create objects for word application and word document
    /// </summary>
    private void createObjects()
    {
        try
        {
            oWord1 = new Microsoft.Office.Interop.Word.ApplicationClass();
            oDoc1 = new Microsoft.Office.Interop.Word.Document();
        }

        catch (Exception ex)
        {

        }
    }

No comments:

Post a Comment