Search code examples
asp.netexport-to-excelimport-from-excel

How to do Import-Export to Excel functionality in ASP.NET?


In my asp.net web application there is a requirement where i have to import and export data to and from an excel. how can i do it?


Solution

  • here is code to export data in excel

    StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        string attachment = "attachment; filename=excel" + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        rptMain.DataBind();
        rptMain.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
    

    and here is code to import Data from Excel

    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
            DbDataAdapter adapter = factory.CreateDataAdapter();
            DbCommand selectCommand = factory.CreateCommand();
            selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = connectionString;
            selectCommand.Connection = connection;
            adapter.SelectCommand = selectCommand;
            DataTable dtbl = new DataTable();
            adapter.Fill(dtbl);
    
            if (dtbl.Rows.Count > 0)
            {
             .............
             .............
            }