Thursday 26 January 2012

Reading .doc or word file using c#.net

1 First ,u need to add Microsoft Office Object Library throgh Add reference/com tab
2 second add  this namespace Microsoft.Office.Interop.Word;
note :install msoffice 2003 or 2007  (then only u will get Microsoft Office Object Library dlls)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Drawing;

namespace Police_Photo_Identity_Card
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Word Documents(*.doc)|*.doc";
            ofd.ShowDialog();
            txtCurrentFile.Text = ofd.FileName;         
         
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            if (txtCurrentFile.Text.Length > 0)
            {
                readFileContent(txtCurrentFile.Text);
            }
            else
            {
                MessageBox.Show("Enter a valid file path");
            }
        }

        private void readFileContent(string path)
        {
            Microsoft.Office.Interop.Word.ApplicationClass wordApp = new ApplicationClass();
            object file = path;
            object nullobj = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(
                ref file, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj);
            doc.ActiveWindow.Selection.WholeStory();
            doc.ActiveWindow.Selection.Copy();
            IDataObject data = Clipboard.GetDataObject();           
            txtWordData.Text = data.GetData(DataFormats.Text).ToString();           
                    doc.Close(ref nullobj, ref nullobj, ref nullobj);
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);

        }
    }
}

No comments:

Post a Comment