Tuesday, September 10, 2019

how to read excel file using oledbconnnection and display data into gridview




<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GV1" runat="server"></asp:GridView>
        </div>
    </form>
</body>
</html>

Add Connection string into web.config file by following code 

  <connectionStrings>
    <add name ="Excel03ConString"
         connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
                         Extended Properties='Excel 8.0;HDR={1}'"/>
    <add name ="Excel07ConString"
         connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
                         Extended Properties='Excel 8.0;HDR={1}'"/>
  </connectionStrings>

C# Code for read excel file

       string dataFilePath = @" C:\brij2019\sample-data.xlsx";
       
        CommonFunctions cf = new CommonFunctions();
        protected void Page_Load(object sender, EventArgs e)
        {
        getDataFromExcelToGridView();
        }


        protected void getDataFromExcelToGridView()
        {

            string conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
                                .ConnectionString;
            if (conStr != "")
            {
                conStr = String.Format(conStr, dataFilePath, "Yes");
                OleDbConnection connExcel = new OleDbConnection(conStr);
                OleDbCommand cmdExcel = new OleDbCommand();
                OleDbDataAdapter oda = new OleDbDataAdapter();
                DataTable dt = new DataTable();
                cmdExcel.Connection = connExcel;
                connExcel.Open();
                cmdExcel.CommandText = "SELECT * From [Sheet1$]";
                oda.SelectCommand = cmdExcel;
                oda.Fill(dt);
                GV1.DataSource = dt;
                GV1.DataBind();
                connExcel.Close();
            }
        }


Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...