protected void btnExport_Click(object sender, EventArgs e)
{
ExportCSV(CreateData(),"Test")
}
public void ExportCSV(DataTable data, string fileName)
{
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 - 1; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(data.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
//Write data
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < data.Columns.Count - 1; i++)
{
if (i > 0)
{
context.Response.Write(",");
}
context.Response.Write(data.Columns[i].ColumnName);
}
context.Response.Write(Environment.NewLine);
}
context.Response.End();
}
private DataTable CreateData()
{
DataTable table1;
table1 = new DataTable("Customers");
DataRow row1, row2, row3;
DataColumn colName = new DataColumn("CustomerName", System.Type.GetType("System.String"));
DataColumn colCity = new DataColumn("City", System.Type.GetType("System.String"));
table1.Columns.Add(colName);
table1.Columns.Add(colCity);
row1 = table1.NewRow();
row1["CustomerName"] = "Microsoft";
row1["City"] = "Redmond";
table1.Rows.Add(row1);
row2 = table1.NewRow();
row2["CustomerName"] = "Amazon.com";
row2["City"] = "Seattle";
table1.Rows.Add(row2);
row3 = table1.NewRow();
row3["CustomerName"] = "IBM";
row3["City"] = "Armonk";
table1.Rows.Add(row3);
return table1;
}
12 September, 2009
Export CSV File
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment