Export DataTable to Excel and Stream to Browser

By Peter Bromberg

A common requirement for ASP.NET developers is to be able to take a DataTable and stream it as an Excel spreadsheet to the user. This is a "quick and dirty" method that will handle most cases. All you need to do is send in a DataTable and a name for the spreadsheet, and the open dialog comes right up in the user's browser.

public  void ExportToSpreadsheet( DataTable table, string name )
    {
         // remove any interior commas in string rows and replace with spaces so as not to mess up column parsing
        foreach (DataRow row in table.Rows)
        {
             for (int i = 0; i < row.ItemArray.Length; i++)
            {
                 if (row[i] is string && ((string)row[i]).Contains(","))
                    row[i] = ((string)row[i]).Replace(",", " ");
            }
        }
       HttpContext context = HttpContext.Current;
        context.Response.Clear();
        foreach (DataColumn column in table.Columns)
        {
             context.Response.Write(column.ColumnName + ",");
        }
         context.Response.Write(Environment.NewLine);
        foreach (DataRow row in table.Rows)
        {
             for (int i = 0; i < table.Columns.Count; i++)
            {
                 context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ",");
            }
            context.Response.Write(Environment.NewLine);
        }
         context.Response.ContentType = "text/csv";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
        context.Response.End();
    }

Export DataTable to Excel and Stream to Browser  (1847 Views)