我无法将数据导出到Excel。以下似乎将gridview渲染到我的View中,而不是提示用户使用我在我的机器上安装的Excel进行打开。
Public ActionResult ExportToExcel() { var products = this.Repository.Products.ToList(); var grid = new GridView(); grid.DataSource = from p in products select new { Id = p.Id,Name = p.Name }; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; response.addheader("content-disposition","attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); return View("MyView"); }
我究竟做错了什么?
解决方法
我已经尝试了你的代码,它的工作正常。
该文件正在创建没有任何问题,这是我使用的代码(这是你的代码,我只是更改了数据源进行测试):
该文件正在创建没有任何问题,这是我使用的代码(这是你的代码,我只是更改了数据源进行测试):
public ActionResult ExportToExcel() { var products = new System.Data.DataTable("teste"); products.Columns.Add("col1",typeof(int)); products.Columns.Add("col2",typeof(string)); products.Rows.Add(1,"product 1"); products.Rows.Add(2,"product 2"); products.Rows.Add(3,"product 3"); products.Rows.Add(4,"product 4"); products.Rows.Add(5,"product 5"); products.Rows.Add(6,"product 6"); products.Rows.Add(7,"product 7"); var grid = new GridView(); grid.DataSource = products; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; response.addheader("content-disposition","attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); return View("MyView"); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。