下载Excel文件 [英] Downloading Excel File

查看:192
本文介绍了下载Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前也问过这个,但我仍然有发起文件下载困难。

I have asked this before but am still having difficulties in initiating the file download.

var fileName = "ExcelData.xlsx";
var file = new FileInfo(fileName);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
   var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Employee Data");
   if (package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Employee Data") == null)
   {
       worksheet = package.Workbook.Worksheets.Add("Employee Data");
   }
   else
   {
       package.Workbook.Worksheets.Delete(1);
       worksheet = package.Workbook.Worksheets.Add("Employee Data");
    }
     worksheet.Cells[1, 1].Value = "Date start";
     worksheet.Cells[1, 2].Value = "Name";

     var rowCounter = 2;
      foreach (var v in users)
      {
         string dt = v.DateAdded.ToString();
         worksheet.Cells[rowCounter, 1].Value = dt;
         worksheet.Cells[rowCounter, 2].Value = v.Name;
         rowCounter++;
      }
      package.Workbook.Properties.Title = "Employee Data";

      System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
      response.Clear();
      response.Buffer = true;
      response.Charset = "";
      response.ContentType = "application/vnd.openxmlformats-     officedocument.spreadsheetml.sheet";
      response.AddHeader("content-disposition", "attachment;filename=ExcelData.xlsx");
      response.BinaryWrite(package.GetAsByteArray());
}



由于它是在没有出现错误的时刻,但在下载也不会触发。我如何触发下载,这样生成的文件保存到默认的下载文件夹

As it is at the moment no errors occur but the download is also not triggered. How do I trigger the download so that the generated file is saved to a default download folder

推荐答案

你为什么不返回 FileContentResult

由于您使用可以返回片作为字节数组Excel的库,这可能是工作的你

Since the Excel library you are using can return the sheet as a byte array, this could work for you.

在你的控制器,你可以返回 FileContentResult 是这样的:

In your controller, you can just return the FileContentResult like this:

return File(package.GetAsByteArray(), "application/xlsx", "YourReportName.xlsx");



所以,你可以从你的代码中删除此块:

So you can remove this block from you code:

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
  response.Clear();
  response.Buffer = true;
  response.Charset = "";
  response.ContentType = "application/vnd.openxmlformats-     officedocument.spreadsheetml.sheet";
  response.AddHeader("content-disposition", "attachment;filename=ExcelData.xlsx");
  response.BinaryWrite(package.GetAsByteArray());

和刚刚回归的文件,如上图所示。

and just return the File as shown above.

只要注意你必须using语句添加到您的控制器 System.Web.Mvc

Just note you have to add a using statement to your controller for System.Web.Mvc.

这篇关于下载Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆