You can use ExportDataTable method to export a generic datatable content to a CSV format.
The following sample is used in ASP.NET context to export the result of a gridview. This code-sample should be place in the handler method of a click button event.
protected void LinkButtonExportAsExcel_Click(object sender, EventArgs e)
{
try
{
DataView dataView = (DataView)Cache["DataSource"];
if (dataView == null) dataView = GetDataView();
char[] bufferedExport = ExportDataTable(dataView.Table, "CSV");
if (bufferedExport == null) return;
Response.Clear();
Response.ContentType = "text/csv";
Response.ContentEncoding = Encoding.Default;
Response.Charset = Encoding.Default.EncodingName;
Response.AddHeader("Content-Disposition", "attachment;filename=Export.csv");
Response.AddHeader("Content-Length",
Encoding.Default.GetByteCount(bufferedExport).ToString());
Response.BinaryWrite(Encoding.Default.GetBytes(bufferedExport));
Response.Flush(); //Instead of ‘Response.End’
//(cf : http://support.microsoft.com/kb/312629/EN-US/)
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
//…
}
}
public static char[] ExportDataTable(DataTable table, string format)
{
string fieldSeparator;
string containerSeparator, containerSeparatorReplace;
string carriageReturn;
switch (format.ToUpper())
{
case "CSV":
fieldSeparator = ",";
containerSeparator = "\"";
containerSeparatorReplace = containerSeparator + containerSeparator;
carriageReturn = "\r\n";
return ExportDataTable(table, fieldSeparator,
containerSeparator, containerSeparatorReplace, carriageReturn);
default:
return null;
}
}
public static char[] ExportDataTable(
DataTable table,
string fieldSeparator,
string containerSeparator, string containerSeparatorReplace,
string carriageReturn)
{
string temp;
StringBuilder contentBuffer = new StringBuilder();
StringBuilder headerBuffer = new StringBuilder();
int rowIndex = 0;
foreach (DataRow row in table.Rows)
{
int columnIndex = 0;
foreach (DataColumn column in table.Columns)
{
if (row[column.ColumnName] != DBNull.Value)
{
if (column.DataType == typeof(System.String))
{
temp = (string)row[column.ColumnName];
temp = temp.Trim();
temp = temp.Replace(containerSeparator, containerSeparatorReplace);
contentBuffer.Append(containerSeparator);
contentBuffer.Append(temp);
contentBuffer.Append(containerSeparator);
}
else if (column.DataType == typeof(System.Int32))
{
contentBuffer.Append(Convert.ToString((int)row[column.ColumnName]));
}
else if (column.DataType == typeof(System.Byte))
{
contentBuffer.Append(Convert.ToString((byte)row[column.ColumnName]));
}
else if (column.DataType == typeof(System.Double))
{
contentBuffer.Append(Convert.ToString((double)row[column.ColumnName]));
}
else if (column.DataType == typeof(System.Decimal))
{
contentBuffer.Append(Convert.ToString((decimal)row[column.ColumnName]));
}
else if (column.DataType == typeof(System.DateTime))
{
contentBuffer.Append(Convert.ToString((DateTime)row[column.ColumnName]));
}
}
if (columnIndex < table.Columns.Count && rowIndex == 0)
headerBuffer.Append(column.ColumnName);
if (columnIndex < table.Columns.Count -1 )
{
if (rowIndex == 0)
headerBuffer.Append(fieldSeparator);
contentBuffer.Append(fieldSeparator);
}
columnIndex++;
}
contentBuffer.Append(carriageReturn);
rowIndex++;
}
headerBuffer.Append(carriageReturn);
contentBuffer.Insert(0, headerBuffer.ToString());
return contentBuffer.ToString().ToCharArray();
}
}