I think I just need a fresh set of eyes to look at the following code. I've got a page that fills a DataTable with user information from our Active Directory. I want to have a button that dumps all that information to a .csv file for a user to download. Unfortunately it doesn't give me anything but the "Open/Save" dialog: clicking either button just gives me an overwhelming sense of nothingness and disappointment. I'd welcome an obvious error at this point...
Regarding the code, "ds" is a globally-defined DataSet. The function "DataTableToCSV" just loops through the given table to create the contents of a CSV string; the "true" argument indicates that I want a header row.
If I comment out the Content-Disposition header, Excel will open but display each line of the CSV in the first cell of the worksheet. Alternatively, I get the raw data in the browser window if I comment out both the Content-Type and Content-Disposition headers. I can manually copy-and-paste this raw data into a .csv file and Excel will recognize it, but that defeats the purpose of having the button. I could just as easily copy-and-paste the GridView into Excel.
protected void CsvButton_Click(object sender, EventArgs e)
DataTable dt = ds.Tables["users"];
String csv = DataTableToCSV(dt, true);
// make sure we only send the CSV to the browser
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=phones.csv; size=" + csv.Length);