-->

How to import /export database data from /to csv/xml/Excel using ASP.NET and C#.


Introduction

In this post, I explain how to import / export database data from / to Excel using ASP.NET and C#.
Import/export data from/to some common format is a very useful technique for transfer data between two other programs/ system on a different platform.
I have also post:      How to export gridview to excel & Word file with formatting in asp.net


Steps :

Steps for import / export database data from/to Excel file.

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for import / export data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one table as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for import, show and export data.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code

  1. <h3>Import / Export database data from/to Excel.</h3>
  2. <div>
  3. <table>
  4. <tr>
  5. <td>Select File : </td>
  6. <td>
  7. <asp:FileUpload ID="FileUpload1" runat="server" />
  8. </td>
  9. <td>
  10. <asp:Button ID="btnImport" runat="server" Text="Import Data" OnClick="btnImport_Click" />
  11. </td>
  12. </tr>
  13. </table>
  14. <div>
  15. <br />
  16. <asp:Label ID="lblMessage" runat="server" Font-Bold="true" />
  17. <br />
  18. <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
  19. <EmptyDataTemplate>
  20. <div style="padding:10px">
  21. Data not found!
  22. </div>
  23. </EmptyDataTemplate>
  24. <Columns>
  25. <asp:BoundField HeaderText="Employee ID" DataField="EmployeeID" />
  26. <asp:BoundField HeaderText="Company Name" DataField="CompanyName" />
  27. <asp:BoundField HeaderText="Contact Name" DataField="ContactName" />
  28. <asp:BoundField HeaderText="Contact Title" DataField="ContactTitle" />
  29. <asp:BoundField HeaderText="Address" DataField="EmployeeAddress" />
  30. <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
  31. </Columns>
  32. </asp:GridView>
  33. <br />
  34. <asp:Button ID="btnExport" runat="server" Text="Export Data" OnClick="btnExport_Click" />
  35. </div>
  36. </div>

Step-6: Write code into page load event for show data.

Write below code into Page_Load event for show data from database.

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopulateData();
  6. lblMessage.Text = "Current Database Data!";
  7. }
  8. }

   And here is the functioin populateDatabaseData

  1. private void populateDatabaseData()
  2. {
  3. using (MuDatabaseEntities dc = new MuDatabaseEntities())
  4. {
  5. gvData.DataSource = dc.EmployeeMasters.ToList();
  6. gvData.DataBind();
  7. }
  8. }

Step-7: Write code for import Data from EXCEL to database

Write below code into button click event for import Data from EXCEL to the database.

  1. protected void btnImport_Click(object sender, EventArgs e)
  2. {
  3. if (FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel" ||
  4. FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  5. {
  6. try
  7. {
  8. string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.PostedFile.FileName));
  9. FileUpload1.PostedFile.SaveAs(fileName);
  10.  
  11. string conString = "";
  12. string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
  13. if (ext.ToLower() == ".xls")
  14. {
  15. conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; ;
  16. }
  17. else if (ext.ToLower() == ".xlsx")
  18. {
  19. conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
  20. }
  21.  
  22. string query = "Select [Employee ID],[Company Name], [Contact Name],[Contact Title],[Employee Address],[Postal Code] from [EmployeeData$]";
  23. OleDbConnection con = new OleDbConnection(conString);
  24. if (con.State == System.Data.ConnectionState.Closed)
  25. {
  26. con.Open();
  27. }
  28. OleDbCommand cmd = new OleDbCommand(query, con);
  29. OleDbDataAdapter da = new OleDbDataAdapter(cmd);
  30.  
  31. DataSet ds = new DataSet();
  32. da.Fill(ds);
  33. da.Dispose();
  34. con.Close();
  35. con.Dispose();
  36.  
  37. // Import to Database
  38. using (MuDatabaseEntities dc = new MuDatabaseEntities())
  39. {
  40. foreach (DataRow dr in ds.Tables[0].Rows)
  41. {
  42. string empID = dr["Employee ID"].ToString();
  43. var v = dc.EmployeeMasters.Where(a => a.EmployeeID.Equals(empID)).FirstOrDefault();
  44. if (v != null)
  45. {
  46. // Update here
  47. v.CompanyName = dr["Company Name"].ToString();
  48. v.ContactName = dr["Contact Name"].ToString();
  49. v.ContactTitle = dr["Contact Title"].ToString();
  50. v.EmployeeAddress = dr["Employee Address"].ToString();
  51. v.PostalCode = dr["Postal Code"].ToString();
  52. }
  53. else
  54. {
  55. // Insert
  56. dc.EmployeeMasters.Add(new EmployeeMaster
  57. {
  58. EmployeeID = dr["Employee ID"].ToString(),
  59. CompanyName = dr["Company Name"].ToString(),
  60. ContactName = dr["Contact Name"].ToString(),
  61. ContactTitle = dr["Contact Title"].ToString(),
  62. EmployeeAddress = dr["Employee Address"].ToString(),
  63. PostalCode = dr["Postal Code"].ToString()
  64. });
  65. }
  66. }
  67.  
  68. dc.SaveChanges();
  69. }
  70.  
  71. PopulateData();
  72. lblMessage.Text = "Successfully data import done!";
  73. }
  74. catch (Exception)
  75. {
  76. throw;
  77. }
  78. }
  79. }

Step-8: Write code for export Data from a database to EXCEL.

Write below code into button click event for export Data from a database to EXCEL.

  1. protected void btnExport_Click(object sender, EventArgs e)
  2. {
  3. using (MuDatabaseEntities dc = new MuDatabaseEntities())
  4. {
  5. List<EmployeeMaster> emList = dc.EmployeeMasters.ToList();
  6. StringBuilder sb = new StringBuilder();
  7.  
  8. if (emList.Count > 0)
  9. {
  10. string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xlsx");
  11. string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
  12. using (OleDbConnection con = new OleDbConnection(conString))
  13. {
  14. string strCreateTab = "Create table EmployeeData ("+
  15. " [Employee ID] varchar(50), " +
  16. " [Company Name] varchar(200), " +
  17. " [Contact Name] varchar(200), " +
  18. " [Contact Title] varchar(200), " +
  19. " [Employee Address] varchar(200), " +
  20. " [Postal Code] varchar(50))";
  21. if (con.State == ConnectionState.Closed)
  22. {
  23. con.Open();
  24. }
  25.  
  26. OleDbCommand cmd = new OleDbCommand(strCreateTab, con);
  27. cmd.ExecuteNonQuery();
  28.  
  29. string strInsert = "Insert into EmployeeData([Employee ID],[Company Name],"+
  30. " [Contact Name], [Contact Title], [Employee Address], [Postal Code]" +
  31. ") values(?,?,?,?,?,?)";
  32. OleDbCommand cmdIns = new OleDbCommand(strInsert, con);
  33. cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
  34. cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
  35. cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
  36. cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
  37. cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
  38. cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
  39.  
  40. foreach (var i in emList)
  41. {
  42. cmdIns.Parameters[0].Value = i.EmployeeID;
  43. cmdIns.Parameters[1].Value = i.CompanyName;
  44. cmdIns.Parameters[2].Value = i.ContactName;
  45. cmdIns.Parameters[3].Value = i.ContactTitle;
  46. cmdIns.Parameters[4].Value = i.EmployeeAddress;
  47. cmdIns.Parameters[5].Value = i.PostalCode;
  48.  
  49. cmdIns.ExecuteNonQuery();
  50. }
  51. }
  52.  
  53. // Create Downloadable file
  54. byte[] content = File.ReadAllBytes(fileName);
  55. HttpContext context = HttpContext.Current;
  56.  
  57. context.Response.BinaryWrite(content);
  58. context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  59. context.Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeData.xlsx");
  60. Context.Response.End();
  61. }
  62. }
  63. }

Step-9: Run Application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: