Sunday, August 11, 2019

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

Here I explain Part 1, import / export database data from/to CSV 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 tables 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 to / from csv/xml/excel format.</h3>
  2. <div>
  3. <h3>Import / Export data from csv.</h3>
  4. <div>
  5. <table>
  6. <tr>
  7. <td>Select File : </td>
  8. <td>
  9. <asp:FileUpload ID="FileUpload1" runat="server" /></td>
  10. <td>
  11. <asp:Button ID="btnImportFromCSV" runat="server" Text="Import Data to Database" OnClick="btnImportFromCSV_Click" />
  12. </td>
  13. </tr>
  14. </table>
  15. <div>
  16. <br />
  17. <asp:Label ID="lblMessage" runat="server" Font-Bold="true" />
  18. <br />
  19. <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
  20. <EmptyDataTemplate>
  21. <div style="padding:10px;">No Data Found!</div>
  22. </EmptyDataTemplate>
  23. <Columns>
  24. <asp:BoundField HeaderText="Employee ID" DataField="EmployeeID" />
  25. <asp:BoundField HeaderText="Company Name" DataField="CompanyName" />
  26. <asp:BoundField HeaderText="Contact Name" DataField="ContactName" />
  27. <asp:BoundField HeaderText="Contact Title" DataField="ContactTitle" />
  28. <asp:BoundField HeaderText="Address" DataField="EmployeeAddress" />
  29. <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
  30. </Columns>
  31. </asp:GridView>
  32. <br />
  33. <asp:Button ID="btnExportToCSV" runat="server" Text="Export Data to CSV" OnClick="btnExportToCSV_Click" />
  34. </div>
  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. populateDatabaseData();
  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 csv to database

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

  1. protected void btnImportFromCSV_Click(object sender, EventArgs e)
  2. {
  3. if (FileUpload1.PostedFile.ContentType == "text/csv" || FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel")
  4. {
  5. string fileName = Path.Combine(Server.MapPath("~/UploadDocuments"), Guid.NewGuid().ToString() + ".csv");
  6. try
  7. {
  8. FileUpload1.PostedFile.SaveAs(fileName);
  9.  
  10. string[] Lines = File.ReadAllLines(fileName);
  11. string[] Fields;
  12.  
  13. //Remove Header line
  14. Lines = Lines.Skip(1).ToArray();
  15. List<EmployeeMaster> emList = new List<EmployeeMaster>();
  16. foreach (var line in Lines)
  17. {
  18. Fields = line.Split(new char[] { ',' });
  19. emList.Add(
  20. new EmployeeMaster
  21. {
  22. EmployeeID = Fields[0].Replace("\"",""), // removed ""
  23. CompanyName = Fields[1].Replace("\"", ""),
  24. ContactName = Fields[2].Replace("\"", ""),
  25. ContactTitle = Fields[3].Replace("\"", ""),
  26. EmployeeAddress = Fields[4].Replace("\"", ""),
  27. PostalCode = Fields[5].Replace("\"", ""),
  28. });
  29. }
  30.  
  31. // Update database data
  32. using (MuDatabaseEntities dc = new MuDatabaseEntities())
  33. {
  34. foreach (var i in emList)
  35. {
  36. var v = dc.EmployeeMasters.Where(a => a.EmployeeID.Equals(i.EmployeeID)).FirstOrDefault();
  37. if (v != null)
  38. {
  39. v.EmployeeID = i.EmployeeID;
  40. v.CompanyName = i.CompanyName;
  41. v.ContactName = i.ContactName;
  42. v.ContactTitle = i.ContactTitle;
  43. v.EmployeeAddress = i.EmployeeAddress;
  44. v.PostalCode = i.PostalCode;
  45. }
  46. else
  47. {
  48. dc.EmployeeMasters.Add(i);
  49. }
  50. }
  51.  
  52. dc.SaveChanges();
  53.  
  54. // populate updated data
  55. populateDatabaseData();
  56. lblMessage.Text = "Successfully Done. Now upto data is following.....";
  57. }
  58. }
  59. catch (Exception)
  60. {
  61. throw;
  62. }
  63. }
  64. }

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

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

  1. protected void btnExportToCSV_Click(object sender, EventArgs e)
  2. {
  3. List<EmployeeMaster> emList = new List<EmployeeMaster>();
  4. using (MuDatabaseEntities dc = new MuDatabaseEntities())
  5. {
  6. emList = dc.EmployeeMasters.ToList();
  7. }
  8.  
  9. if (emList.Count > 0)
  10. {
  11. string header = @"""Employee ID"",""Company Name"",""Contact Name"",""Contact Title"",""Employee Address"",""Postal Code""";
  12. StringBuilder sb = new StringBuilder();
  13. sb.AppendLine(header);
  14.  
  15. foreach (var i in emList)
  16. {
  17. sb.AppendLine(string.Join(",",
  18. string.Format(@"""{0}""", i.EmployeeID),
  19. string.Format(@"""{0}""", i.CompanyName),
  20. string.Format(@"""{0}""", i.ContactName),
  21. string.Format(@"""{0}""", i.ContactTitle),
  22. string.Format(@"""{0}""", i.EmployeeAddress),
  23. string.Format(@"""{0}""", i.PostalCode)));
  24. }
  25.  
  26. // Download Here
  27.  
  28. HttpContext context = HttpContext.Current;
  29. context.Response.Write(sb.ToString());
  30. context.Response.ContentType = "text/csv";
  31. context.Response.AddHeader("Content-Disposition", "attachment; filename=EmployeeData.csv");
  32. context.Response.End();
  33. }
  34. else
  35. {
  36. lblMessage.Text = "Data not Found!";
  37. }
  38. }
Step-9: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...