asp.net-mvc – 使用ASP.NET MVC导出数据到Excel文件4 C#正在呈
发布时间:2020-12-15 18:48:55 所属栏目:asp.Net 来源:网络整理
导读:我无法将数据导出到Excel。以下似乎将gridview渲染到我的View中,而不是提示用户使用我在我的机器上安装的Excel进行打开。 Public ActionResult ExportToExcel(){ var products = this.Repository.Products.ToList(); var grid = new GridView(); grid.DataS
我无法将数据导出到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"); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- asp.net – 如何从mvc .net web app中的jquery(在
- asp.net – 如何将流excel文件转换为数据表C#?
- 学习ASP.NET MVC从1或2或3开始
- asp.net-mvc-4 – Durandal.js:更改每个区域的导
- asp.net-mvc – 如何开始使用多租户MVC应用程序
- asp.net – 如何禁用提交行为的asp:ImageButton
- 一键将Web应用发布到云-Azure Web App
- asp.net-mvc – 如何使用Ninject注入Identity类?
- asp.net – User.GetUserId()在控制器的构造函数
- asp.net-core – 如何在ASP.NET Core的OpenIdCon
热点阅读