Platform: Visual Studio 2008 with ASP.net
Technology: Used in ASP.net
Level: Beginner
Introduction
1. Add a gridview into a aspx file
2. Add a button into a aspx file and give the name as "btnExportToCSV"
3. Write a code in aspx.cs file
Expand|Select|Wrap|Line Numbers
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- namespace Example
- {
- public partial class ExportFiles : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- DataTable dtRecords = new DataTable();
- dtRecords.Columns.Add("State", typeof(string));
- dtRecords.Columns.Add("City", typeof(string));
- DataRow dr = dtRecords.NewRow();
- dr["State"] = "Karnataka";
- dr["City"] = "Bangalore";
- dtRecords.Rows.Add(dr);
- grdData.DataSource = dtRecords;
- grdData.DataBind();
- }
- protected void btnExportToCSV_Click(object sender, EventArgs e)
- {
- Response.Clear();
- Response.Buffer = true;
- Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
- Response.Charset = "";
- Response.ContentType = "application/text";
- GridView1.AllowPaging = false;
- StringBuilder sb = new StringBuilder();
- for (int k = 0; k < GridView1.Columns.Count; k++)
- {
- sb.Append(GridView1.Columns[k].HeaderText + ',');
- }
- sb.Append("\r\n");
- for (int i = 0; i < GridView1.Rows.Count; i++)
- {
- for (int k = 0; k < GridView1.Columns.Count; k++)
- {
- sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
- }
- sb.Append("\r\n");
- }
- Response.Output.Write(sb.ToString());
- Response.Flush();
- Response.End();
- }
- public override void VerifyRenderingInServerForm(Control control)
- {
- }
- }
- }
Run the application click on button, it will ask to save or open a file, if you save it will be saved into your disk
or if you click on open it directely open the excel file.
References
License