Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Found this in some old code I did like 5 years ago that should work...</p> <pre><code>public static void DataTableToExcel(DataTable tbl) { HttpContext context = HttpContext.Current; context.Response.Clear(); foreach (DataColumn c in tbl.Columns) { context.Response.Write(c.ColumnName + ";"); } context.Response.Write(Environment.NewLine); foreach (DataRow r in tbl.Rows) { for (int i = 0; i &lt; tbl.Columns.Count; i++) { context.Response.Write(r[i].ToString().Replace(";", string.Empty) + ";"); } context.Response.Write(Environment.NewLine); } context.Response.ContentType = "text/csv"; context.Response.AppendHeader("Content-Disposition", "attachment; filename=export.csv"); context.Response.End(); } </code></pre> <p>This will output from ASP.NET a response with a CSV file that Excel 2007 can open. If you want you can change the extension to mimic excel and it should work just by replacing the following lines:</p> <pre><code> context.Response.ContentType = "application/vnd.ms-excel"; context.Response.AppendHeader("Content-Disposition", "attachment; filename=export.xlsx"); </code></pre> <p>A CSV is the easiest way if you don't need to do anything complex. If you do require it to truly be a Excel 2007 file in the native format, you will need to use an Office library to build it or convert it from the CSV and then serve/save it.</p> <p>This link might also be useful:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/afd383e1-54b5-47c6-8817-163dc5d7606c" rel="nofollow noreferrer">How to avoid the Excel prompt window when exporting data to Excel 2007</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload