Friday, April 18, 2014

How to read winword (*.docx) files using C#.net using Office Inerop

How to read winword (*.docx) files using C#.net using Office Inerop



//Reading *.docx files using C#

//Source Code:

using System;
using Microsoft.Office.Interop.Word;

namespace WinwordRead
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                //Load Word file.
                // Import  the Interop Services and  Microsoft.Office.Interop.Word;
      
                Application word = new Application();
                object miss = System.Reflection.Missing.Value;
                object path = @"..\RACode.docx";
                object readOnly = true;

                // Read the word document
                Document docs = word.Documents.Open(ref path, ref miss, ref readOnly,
                ref miss,ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
                ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);

                string totaltext = "";

                // Iterate through paragraphs in docs
                for (int i = 0; i < docs.Paragraphs.Count; i++)
                {
                    totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
                }
                Console.WriteLine(totaltext);

                //Close the docs

                docs.Close();
                word.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

            }

        }
    }
}



No comments:

Post a Comment