C# Tip Article
How to download DataTable in Excel format
Problem
How to download tabular data such as DataTable data in Excel CSV/TSV format.
Solution
To add tabular data download feature in a web page,
(1) Create CSV or TSV content from tabular data such as DataTable. If there is no comma in raw data, CSV is fine. Otherwise, use TSV.
(2) Send CSV/TSV data to web client. Response.Write() can be used for text data, while Response.BinaryWrite() should be used for binary data such as bytes array.
private void DownloadDataFile(DataTable dt) { // Step1 - Create tsv content StringBuilder sb = new StringBuilder(); // (1) add tsv header var columnNames = dt.Columns.Cast().Select(column => column.ColumnName).ToArray(); var headers = string.Join("\t", columnNames); sb.AppendLine(headers); // (2) add tsv rows var rows = dt.AsEnumerable().Select(row => string.Join("\t", row.ItemArray)); foreach (var r in rows) { sb.AppendLine(r); } string tsvContent = sb.ToString(); // Step2 - Send data to web client Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=data.tsv"); Response.ContentType = "application/octet-stream"; Response.Write(tsvContent); Response.End(); }