Snippets Code
CSVHelper.cs
/// <summary>
/// Export Helper Function - DataGrid to CSV
/// Converted from this article
/// http://www.dotnetbips.com/386541cb-7e0f-491f-b86a-f9bc8be738b8.aspx?articleid=302
/// </summary>
/// <param name="ds"></param>
/// <param name="exportColumnHeadings"></param>
/// <returns></returns>
public string Export(DataSet ds, bool exportColumnHeadings)
{string header = string.Empty;
string body = string.Empty;
string record = string.Empty;
// If you want column to be part of the CSV ...
if (exportColumnHeadings)
{foreach (DataColumn col in ds.Tables[0].Columns)
{header = header + (char)34 + col.ColumnName + (char)34 + ",";
}
header = header.Substring(0, header.Length - 1);
}
// Iterate into the rows
foreach (DataRow row in ds.Tables[0].Rows)
{Object[] arr = row.ItemArray;
for (int i = 0; i < arr.Length - 1; i++)
{if (arr[i].ToString().IndexOf(",") > 0){record = record + (char)34 + arr[i].ToString() + (char)34 + ",";
}
else
{record = record + arr[i].ToString() + ",";
}
}
body = body + record.Substring(0, record.Length - 1) + Environment.NewLine;
record = "";
}
if (exportColumnHeadings)
{return (header + Environment.NewLine + body);
}
else
{return body;
}
}
Export.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{// Put user code to initialize the page here
if (!IsPostBack)
{BindGrid();
}
}
// Retrieve the customer information and bind into the datagrid
void BindGrid()
{SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", "data source=wenching;initial catalog=northwind;user id=sa; password=Passw0rd");DataSet ds = new DataSet();
da.Fill(ds, "customers");
Session["myds"] = ds;
dgResults.DataSource = ds;
dgResults.DataBind();
}
private void btnExport_Click(object sender, System.EventArgs e)
{DataSet ds = (DataSet)Session["myds"];
CSVHelper csv = new CSVHelper();
string strData = csv.Export(ds, chbExport.Checked);
byte[] data = ASCIIEncoding.ASCII.GetBytes(strData);
Response.Clear();
// Set as Excel as the primary format
Response.AddHeader("Content-Type", "application/Excel");// Save the output as customer.csv
Response.AddHeader("Content-Disposition", "inline;filename=customer.csv");Response.BinaryWrite(data);
Response.End();
}