C# Return 文件无法下载 Excel 文件
C# Return File not working to download an Excel file
我正在尝试使用 MVC 项目下载这样的文件:
控制器:
[HttpPost]
[ActionName("ExportList")]
public async Task<IActionResult> ExportList(List<object> objectList)
{
var fileName = "fileName" ".xlsx";
try
{
var fileContent = await _serviceLayer.ExportListToExcel(objectList);
return File(fileContent, "application/vnd.ms-excel", fileName);
// return new JsonResult("ok");
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
然后我的服务层:
public Task<byte[]> ExportListToExcel(List<object> objectList)
{
try
{
using(var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Report");
var currentRow = 1;
#region Header
worksheet.Cell(currentRow, 1).Value = "val1";
worksheet.Cell(currentRow, 2).Value = "val2";
worksheet.Cell(currentRow, 3).Value = "val3";
#endregion
#region Body
foreach(var obj in objectList)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = obj.val1;
worksheet.Cell(currentRow, 2).Value = obj.val2;
worksheet.Cell(currentRow, 3).Value = obj.val3;
}
#endregion
using(var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return Task.FromResult(content);
}
}
}
catch (Exception ex)
{
throw new Exception("Error");
}
}
我调用控制器方法 ajax:
function exportList() {
$.ajax({
type: "POST",
url: "@Url.Action("ExportList")",
data: { objectList: objectList},
dataType: "json",
success: function (data) {
//show success message
}, error: function (req, status, error) {
//show error message
}
});
}
我读了很多帖子,这基本上是他们建议下载文件的内容,但我返回到视图时出现以下错误消息,文件没有被下载,但控制器没有抛出任何类型的异常消息:
有下载文件的想法吗?
试试 Blob
responseType
,
$.ajax({
type: "POST",
url: "@Url.Action("ExportList")",
data: { objectList: objectList},
xhrFields: {
responseType: 'blob' // FileContentResult will return as blob
},
success: function (data) {
const url = window.URL.createObjectURL(data); // create url from blob
const link = document.createElement('a'); // create anchor at DOM
link.href = url;
link.setAttribute('download', 'file.xlsx'); // download attribute
document.body.appendChild(link);
link.click(); // trigger click for download
},
error: function (req, status, error) {
//show error message
}
});
您好,您的问题是 javascript 函数 exportList()
最好在文件所在的位置创建重定向,然后下载它。
在您的导出方法中
这将是您的 ExportList 控制器方法的一部分:
// Generate a new unique identifier against which the file can be stored
string handle = Guid.NewGuid().ToString();
using (MemoryStream memoryStream = new MemoryStream())
{
//save your file to memory stream
workbook.SaveAs(memoryStream);
memoryStream.Position = 0;
TempData[handle] = memoryStream.ToArray();
}
// Note we are returning a filename as well as the handle
return new JsonResult()
{
Data = new { FileGuid = handle, FileName = "exporfile.xlsx" , FileType="xlsx"}
};
您的下载文件应如下所示:
public virtual ActionResult Download(string fileGuid, string fileName, string fileType)
{
if (TempData[fileGuid] != null)
{
byte[] data = TempData[fileGuid] as byte[];
if (fileType == "xlsx" || fileType == "xls")
{
return File(data, "application/vnd.ms-excel", fileName);
}
else if (fileType == "pdf")
{
return File(data, "application/pdf", fileName);
}
else
{
//sin especificar...
return File(data, "application/octet-stream", fileName);
}
}
else
{
return new EmptyResult();
}
}
然后更改您的导出列表方法:
function exportList() {
$.ajax({
type: "POST",
url: "@Url.Action("ExportList")",
data: { objectList: objectList},
dataType: "json",
success: function (data) {
var response = JSON.parse(data);
window.location = '/YourController/Download?fileGuid=' + response.FileGuid + '&filename=' + response.FileName +'&fileType=' + response.FileType;
}, error: function (req, status, error) {
//show error message
}
});
}
我正在尝试使用 MVC 项目下载这样的文件:
控制器:
[HttpPost]
[ActionName("ExportList")]
public async Task<IActionResult> ExportList(List<object> objectList)
{
var fileName = "fileName" ".xlsx";
try
{
var fileContent = await _serviceLayer.ExportListToExcel(objectList);
return File(fileContent, "application/vnd.ms-excel", fileName);
// return new JsonResult("ok");
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
然后我的服务层:
public Task<byte[]> ExportListToExcel(List<object> objectList)
{
try
{
using(var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Report");
var currentRow = 1;
#region Header
worksheet.Cell(currentRow, 1).Value = "val1";
worksheet.Cell(currentRow, 2).Value = "val2";
worksheet.Cell(currentRow, 3).Value = "val3";
#endregion
#region Body
foreach(var obj in objectList)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = obj.val1;
worksheet.Cell(currentRow, 2).Value = obj.val2;
worksheet.Cell(currentRow, 3).Value = obj.val3;
}
#endregion
using(var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return Task.FromResult(content);
}
}
}
catch (Exception ex)
{
throw new Exception("Error");
}
}
我调用控制器方法 ajax:
function exportList() {
$.ajax({
type: "POST",
url: "@Url.Action("ExportList")",
data: { objectList: objectList},
dataType: "json",
success: function (data) {
//show success message
}, error: function (req, status, error) {
//show error message
}
});
}
我读了很多帖子,这基本上是他们建议下载文件的内容,但我返回到视图时出现以下错误消息,文件没有被下载,但控制器没有抛出任何类型的异常消息:
有下载文件的想法吗?
试试 Blob
responseType
,
$.ajax({
type: "POST",
url: "@Url.Action("ExportList")",
data: { objectList: objectList},
xhrFields: {
responseType: 'blob' // FileContentResult will return as blob
},
success: function (data) {
const url = window.URL.createObjectURL(data); // create url from blob
const link = document.createElement('a'); // create anchor at DOM
link.href = url;
link.setAttribute('download', 'file.xlsx'); // download attribute
document.body.appendChild(link);
link.click(); // trigger click for download
},
error: function (req, status, error) {
//show error message
}
});
您好,您的问题是 javascript 函数 exportList() 最好在文件所在的位置创建重定向,然后下载它。 在您的导出方法中
这将是您的 ExportList 控制器方法的一部分:
// Generate a new unique identifier against which the file can be stored
string handle = Guid.NewGuid().ToString();
using (MemoryStream memoryStream = new MemoryStream())
{
//save your file to memory stream
workbook.SaveAs(memoryStream);
memoryStream.Position = 0;
TempData[handle] = memoryStream.ToArray();
}
// Note we are returning a filename as well as the handle
return new JsonResult()
{
Data = new { FileGuid = handle, FileName = "exporfile.xlsx" , FileType="xlsx"}
};
您的下载文件应如下所示:
public virtual ActionResult Download(string fileGuid, string fileName, string fileType)
{
if (TempData[fileGuid] != null)
{
byte[] data = TempData[fileGuid] as byte[];
if (fileType == "xlsx" || fileType == "xls")
{
return File(data, "application/vnd.ms-excel", fileName);
}
else if (fileType == "pdf")
{
return File(data, "application/pdf", fileName);
}
else
{
//sin especificar...
return File(data, "application/octet-stream", fileName);
}
}
else
{
return new EmptyResult();
}
}
然后更改您的导出列表方法:
function exportList() {
$.ajax({
type: "POST",
url: "@Url.Action("ExportList")",
data: { objectList: objectList},
dataType: "json",
success: function (data) {
var response = JSON.parse(data);
window.location = '/YourController/Download?fileGuid=' + response.FileGuid + '&filename=' + response.FileName +'&fileType=' + response.FileType;
}, error: function (req, status, error) {
//show error message
}
});
}