現在、データテーブルからc#asp.netmvc3のExcelシートにデータをエクスポートしようとしています。私はインターネットをサーフィンして、データテーブルをExcelシートにエクスポートするためのいくつかのコードを見つけました。エラーなしで実行されます。ただし、Excelシートは作成されません。これを行うための提案。
string filename = "DownloadMobileNoExcel.xls";
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename="
+ filename + "");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
//Convert the rendering of the gridview to a string representation
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dgGrid.RenderControl(htw);
//Open a memory stream that you can use to write back to the response
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
//Write the stream back to the response
Response.Write(sr.ReadToEnd());
Response.End();