Code Snippet
- <%@ Page Language="C#" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head>
- <title>Export To CSV</title>
- <script runat="server">
- public static void ExportCSV(System.Data.DataTable data, string fileName)
- {
- try
- {
- HttpContext context = HttpContext.Current;
- context.Response.Clear();
- context.Response.ContentType = "text/csv";
- context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
- //rite column header names
- for (int i = 0; i < data.Columns.Count; i++)
- {
- if (i > 0)
- {
- context.Response.Write(",");
- }
- context.Response.Write(data.Columns[i].ColumnName);
- }
- context.Response.Write(Environment.NewLine);
- //Write data
- foreach (System.Data.DataRow row in data.Rows)
- {
- for (int i = 0; i < data.Columns.Count; i++)
- {
- if (i > 0)
- {
- context.Response.Write(",");
- }
- context.Response.Write(row[i].ToString());
- }
- context.Response.Write(Environment.NewLine);
- }
- context.Response.End();
- }
- catch (Exception ex)
- {
- }
- }
- private System.Data.DataTable CreateDataTable()
- {
- System.Data.DataTable dataTable = new System.Data.DataTable("Employee");
- dataTable.Columns.Add(new System.Data.DataColumn("ID", typeof(int)));
- dataTable.Columns.Add(new System.Data.DataColumn("Name", typeof(string)));
- dataTable.Columns.Add(new System.Data.DataColumn("Address", typeof(string)));
- System.Data.DataRow dataRow;
- dataRow = dataTable.NewRow();
- dataRow["ID"] = "1";
- dataRow["Name"] = "sandeep";
- dataRow["Address"] = "Ncode";
- dataTable.Rows.Add(dataRow);
- return dataTable;
- }
- protected void btnExportDataTableToCSV_Click(object sender, EventArgs e)
- {
- ExportCSV(CreateDataTable(), "FileName");
- }
- </script>
- </head>
- <body>
- <h3>FileUpload.SaveAs Method Example</h3>
- <form id="Form1" runat="server">
- <asp:Button ID="btnExportDataTableToCSV" runat="server" OnClick="btnExportDataTableToCSV_Click" Text="Export DataTable to CSV" />
- </form>
- </body>
- </html>
0 comments:
Post a Comment