目前我正在尝试将数据表中的数据导出到 c# asp.net mvc3 中的 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();