.NET provides a very simple way to import, read and export .CSV files.

Now I will create an ASP.Net application where I will bind a grid with the imported .CSV file.

Then you can also export the displayed data in CSV file format.

Step 1

In Visual Studio 2013 first create a simple web application and add a web form just like “Default.aspx”.

default

Step 2

Add a folder like “upload” for storing the imported .CSV file.

Step 3

Prepare a .CSV file for import in the following format.

id

Step 4

Add the following controls to the Deafult.aspx file.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>Import/Export/Read CSV file</title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <div id="dvforgeneratingexcel">
  11. <div>
  12. <asp:GridView ID="wdgList" runat="server" Height="410px" AutoGenerateColumns="False"
  13. Style="width: 99.8%;">
  14. <Columns>
  15. <asp:BoundField DataField="ID" HeaderText="ID"></asp:BoundField>
  16. <asp:BoundField DataField="Name" HeaderText="Name"></asp:BoundField>
  17. </Columns>
  18. </asp:GridView>
  19. </div>
  20. <div class="pull-right">
  21. <asp:Button runat="server" ID="btnExport" Text="Export" OnClick="btnExport_OnClick" />
  22. </div>
  23. </div>
  24. <div id="dvforexcelimport">
  25. <asp:FileUpload Width="300" ID="FileUpload1" CssClass="form-control" runat="server" />
  26. <asp:Button ID="btn_import" runat="server" CssClass="btn btn-default" Text="Upload Excel sheet" OnClick="btn_import_Click" />
  27. </div>
  28. </div>
  29. </form>
  30. </body>
  31. </html>
Step 5
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.OleDb;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Web;
  9. using System.Web.UI;
  10. using System.Web.UI.WebControls;
  11. public partial class _Default : System.Web.UI.Page
  12. {
  13. DataTable dt = new DataTable();
  14. DataTable CSVTable = new DataTable();
  15. protected void Page_Load(object sender, EventArgs e)
  16. {
  17. }
  18. /// <summary>
  19. /// Exporting of the .CSV file.
  20. /// </summary>
  21. /// <param name="sender"></param>
  22. /// <param name="e"></param>
  23. protected void btnExport_OnClick(object sender, EventArgs e)
  24. {
  25. try
  26. {
  27. Response.Clear();
  28. Response.ClearContent();
  29. StringBuilder sb = new StringBuilder();
  30. sb.AppendLine("ID,Name");
  31. Response.ContentType = "application/x-msexcel";
  32. Response.AddHeader("content-disposition", "attachment; filename=ManageList.csv");
  33. Response.Write(sb.ToString());
  34. if (ViewState["CSVTable"] != "")
  35. {
  36. dt = ViewState["CSVTable"] as DataTable;
  37. if ((dt != null) && (dt.Rows.Count > 0))
  38. {
  39. foreach (DataRow row in dt.Rows)
  40. {
  41. sb = new StringBuilder((string)row[0]);
  42. for (int i = 1; i < dt.Columns.Count; i++)
  43. {
  44. if (row[i] is DBNull)
  45. sb.Append(",NULL");
  46. else if (i == 2)
  47. sb.Append("," + new DateTime((long)row[i]).ToString("G"));
  48. else
  49. sb.Append("," + row[i].ToString());
  50. }
  51. sb.AppendLine();
  52. Response.Write(sb.ToString());
  53. }
  54. }
  55. }
  56. Response.Flush();
  57. Response.Close();
  58. Response.End();
  59. }
  60. catch (Exception ex) { }
  61. }
  62. /// <summary>
  63. /// Importing of .CSV file.
  64. /// </summary>
  65. /// <param name="sender"></param>
  66. /// <param name="e"></param>
  67. protected void btn_import_Click(object sender, EventArgs e)
  68. {
  69. try
  70. {
  71. if (FileUpload1.HasFile)
  72. {
  73. int flag = 0;
  74. string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
  75. string RandomName = DateTime.Now.ToFileTime().ToString();
  76. string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
  77. string FolderPath ="~/upload/";
  78. string FilePath = Server.MapPath(FolderPath + RandomName + FileName);
  79. string[] filenames = Directory.GetFiles(Server.MapPath("~/upload"));
  80. if (filenames.Length > 0)
  81. { foreach (string filename in filenames)
  82. {
  83. if (FilePath == filename)
  84. {
  85. flag = 1;
  86. break;
  87. }
  88. }
  89. if (flag == 0)
  90. {
  91. FileUpload1.SaveAs(FilePath);
  92. ReadCSVFile(FilePath);
  93. }
  94. }
  95. else
  96. {
  97. FileUpload1.SaveAs(FilePath);
  98. ReadCSVFile(FilePath);
  99. }
  100. }
  101. else
  102. {
  103. String msg = "Select a file then try to import";
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. throw ex;
  109. }
  110. }
  111. /// <summary>
  112. /// Reading of the .CSV file.
  113. /// </summary>
  114. /// <param name="fileName"></param>
  115. public void ReadCSVFile(string fileName)
  116. {
  117. try {
  118. string connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}\\;Extended Properties='Text;HDR=Yes;FMT=CSVDelimited'";
  119. connection = String.Format(connection, Path.GetDirectoryName(fileName));
  120. OleDbDataAdapter csvAdapter;
  121. csvAdapter = new OleDbDataAdapter("SELECT * FROM [" + Path.GetFileName(fileName) + "]", connection);
  122. if (File.Exists(fileName) && new FileInfo(fileName).Length > 0)
  123. {
  124. try
  125. { csvAdapter.Fill(CSVTable);
  126. if ((CSVTable != null) && (CSVTable.Rows.Count > 0))
  127. {
  128. ViewState["CSVTable"] = CSVTable;
  129. wdgList.DataSource = CSVTable;
  130. wdgList.DataBind();
  131. }
  132. else
  133. {
  134. String msg = "No records found";
  135. }
  136. }
  137. catch (Exception ex)
  138. {
  139. throw new Exception(String.Format("Error reading Table {0}.\n{1}", Path.GetFileName(fileName), ex.Message));
  140. }
  141. }
  142. }
  143. catch (Exception ex) { }
  144. }
  145. }
Thanks.