Wednesday 9 May 2012

Extract the data from the file

Extract the data from the file uploaded, and show it on the web page :

Using a file uploader control, the file is being uploaded and the filepath has been retrieved , then the data of the file is extracted. The code below will extract the word/ excel files' data. The "microsoft word" reference must be added :

using Microsoft.Office.Interop;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.Office.Interop.Word;

protected void Button1_Click(object sender, EventArgs e)
    {
      
        object filePath = (object)FileUpload1.PostedFile.FileName;// ur filepath...
       
      ApplicationClass wordApp = new ApplicationClass();


    object nullobj = System.Reflection.Missing.Value;

    Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(
    ref filePath, ref nullobj, ref nullobj,
    ref nullobj, ref nullobj, 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();

    string sFileText = doc.Content.Text;

    doc.Close(ref nullobj, ref nullobj, ref nullobj);

    wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);

    Response.Write(sFileText);
  }



For the PDF file the code is :

 



 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        string filePath = FileUpload1.PostedFile.FileName.ToString();  //ur file path on the server
        Response.ContentType = "application/pdf";    //"application/ms-word";
        Response.WriteFile(filePath);
    }


For the Text /notepad file the code will be:



System.IO.StreamReader sr = new System.IO.StreamReader(filePath);
        string line;
        while (sr.Peek() != -1)
        {
            Response.Clear();
            line = sr.ReadLine();
            Response.Write(Server.HtmlEncode(line) + "<br/>");
         }

No comments:

Post a Comment