Wednesday 19 February 2014

how to fetch data from the Excel file

 OR
how to get data from the Excel  file
-- > add name space in your code behind file

using System.IO;

--> next following code paste in your code behind file
------------------------------------------------------------------------------------------------
    StreamReader objReader;
    string fileExt = System.IO.Path.GetExtension("Your Excel file");
    //File name for get extension of the file
    if (fileExt == ".csv" || fileExt == ".CSV")
    {
    int linenum =0;
    objReader = new StreamReader(Server.MapPath("Your Excel file"));
    do
    {
                    textline = objReader.ReadLine();
                    if (textline != "")
                    {
                        string[] Data;
                        Data;= textline.Split(',');
                       // your Excel file in first row all data in array member by splite function

                       // You can split data in array like following changes

                         /* string[] data = line.Split('-');
                         string[] data = line.Split('/');
                         string[] data = line.Split('/');
                         string[] data = line.Split(' ');
                         string[] data = line.Split('Your specific character');   
                         */       
                      //now Your data in array and you use follows
         string code = data[0];
        string name = data[1];
        string date = data[2]; 

        // you can create sql query for insert above data (data[0],data[1]....) data in database
                        if (linenum == 0)
                        {
                         }
                        linenum++;//it is for change new line or next line in notepad file
                        }
                    }
                } while (objReader.Peek() != -1);// it is for end of the file
            }
            else //when file is not excel then message
            {
                Label1.Text="Select .CSV File only</span>";
            }

--> above function use on click event and fetch data from the Excel file

No comments:

Post a Comment



Asp.net tutorials