导出excel在MVC中显示在浏览器中,而不是下载文件
本文关键字:下载 文件 浏览器 excel MVC 显示 导出 | 更新日期: 2023-09-27 18:11:29
我试图在excel格式导出我的webgrid数据,但它在浏览器中编写内容而不是下载它。这是我的代码,我参考了很多例子,每个人都告诉一样,但没有一个工作。这是我的代码
var northwind = Database.Open("Northwind");
var sql = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers";
var customers = northwind.Query(sql);
var connString = string.Format(@"Provider=Microsoft.Jet.OleDb.4.0;
Data Source={0}/{1};Extended Properties='Excel 8.0;HDR=Yes;'",
appData, newFileName);
var provider = "System.Data.OleDb";
using (var excel = Database.OpenConnectionString(connString, provider)){
sql = @"INSERT INTO [Sheet1$] (CustomerID, CompanyName, ContactName, Address, City, Country, Phone)
VALUES (@0,@1,@2,@3,@4,@5,@6)";
foreach(var customer in customers){
excel.Execute(sql,
customer.CustomerID,
customer.CompanyName,
customer.ContactName,
customer.Address,
customer.City,
customer.Country,
customer.Phone);
}
}
Response.AddHeader("Content-disposition", "attachment; filename=report.xls");
Response.ContentType = "application/octet-stream";
Response.TransmitFile(newFile);
Response.Flush();
File.Delete(newFile);
Response.End();
和我的观点是
<script type="text/javascript">
$(function () {
$('#excel').appendTo($('tfoot tr td')).on('hover', function () {
$(this).css('cursor', 'pointer');
});
$('#excel').on('click', function () {
$('<iframe src="/GenerateExcel"></iframe>').appendTo('body').hide();
});
});
</script>
@{
Page.Title = "Export To Excel";
var db = Database.Open("Northwind");
var query = "SELECT CustomerID, CompanyName, ContactName, Address, City, Country, Phone FROM Customers";
var data = db.Query(query);
var grid = new WebGrid(data, ajaxUpdateContainerId: "grid");
}
<h1>Export to Excel</h1>
<div id="gridContainer">
<div id="grid">
@grid.GetHtml(
tableStyle : "table",
alternatingRowStyle : "alternate",
headerStyle : "header",
columns: grid.Columns(
grid.Column("CustomerID", "ID"),
grid.Column("CompanyName", "Company Name"),
grid.Column("ContactName", "Contact Name"),
grid.Column("Address"),
grid.Column("City"),
grid.Column("Country"),
grid.Column("Phone")
)
)
<img src="/images/excel-icon.png" id="excel" alt="Export to Excel" title="Export to Excel" />
</div>
</div>
上面的代码我发现在下面的网站,并试图重现相同的,但在浏览器中编写的内容,而不是下载。这是来源
http://www.mikesdotnetting.com/Article/207/Exporting-The-Razor-WebGrid-To-Excel-Using-OleDb请帮忙好吗?
我使用下面的代码来实现这个目的。
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=download.xlsx");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
content.CopyTo(context.Response.OutputStream); //content is the file stream
Response.End();
所以不要使用TransmitFile方法,尝试使用Response.OutputStream.
尝试将Response.ContentType
更改为
Response.ContentType = "application/ms-excel";