如何使用EPPlus和MVC从服务器下载.xslx文件

本文关键字:服务器 下载 xslx 文件 MVC 何使用 EPPlus | 更新日期: 2023-09-27 18:34:02

我有一个使用 EPPlus 在服务器上生成的 Excel 文件,该文件是正确制作的,并使用 window.location 在本地计算机上工作正常,但在部署到服务器时什么也不做。我正在尝试通过 MVC 控制器返回文件流结果,但我认为它不起作用。我正在使用 ajax 调用来访问控制器方法,但在方法运行时它无法输入 .done。

我一直在看 ASP.NET MVC EPPlus下载Excel文件作为我的C#参考。

脚本

 function exportToExcel() {
    var batchName = $("#batchDateSelect option:selected").text();
    var bID = $("#batchDateSelect").val();
    var params = {
        BatchID: bID,
        BatchName: batchName
    };
    $.post(path + "Export/ExportToExcel", params)
    .done(function (Data, textStatus, jqXHR) {
        var fileName = "";
        ////window.location = path + "ExportFiles/"+fileName;
    });
}

控制器

public ActionResult ExportToExcel(int BatchID,string BatchName)
{
    FileStreamResult FSR = DataAccess.ExportUtility.CreateExcelFile(BatchID, BatchName);
    return FSR;
}

EPPlus 方法

public static FileStreamResult CreateExcelFile(int batchid,string batchName)
    {
        string fileName = batchName + " Reason_Code_Export.xlsx";
        var serverPath = HttpContext.Current.Server.MapPath("~/ExportFiles/");
        DirectoryInfo outputDir = new DirectoryInfo(serverPath);
        FileInfo newfile = new FileInfo(outputDir.FullName + fileName);
        if (newfile.Exists)
        {
            newfile.Delete();
            newfile = new FileInfo(outputDir.FullName + fileName);
        }
        Dictionary<string,int> MAData = PolicyDataAccess.GetMatchActionData(batchid);
        MemoryStream MS = new MemoryStream();
        using (ExcelPackage package = new ExcelPackage(newfile))
        {
            ..........
            ........
            package.SaveAs(MS);
        }
        MS.Position = 0;
        var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        FileStreamResult FSR = new FileStreamResult(MS, contentType);
        FSR.FileDownloadName = fileName;

        return FSR;
    }

获取该文件的最简单方法是什么?

如何使用EPPlus和MVC从服务器下载.xslx文件

这个问题我迟到了,但可能对其他人有帮助。

设置Excel工作表后,无需保存或将其添加到MemoryStream中,只需将字节数组作为打包即可。GetAsByteArray() 并从您的操作中将其作为文件而不是 FileStreamResult 返回

var FileBytesArray = packge.GetAsByteArray();
return File(FileBytesArray, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename + ".xlsx");

    EPPLUS 让我有些头疼。
我对 MVC 不是很熟悉,但我假设你想做一些直接写入输出响应的事情。 在这种情况下,我使用如下所示的内容.
我看到我在评论中留下了内存流写入也可以工作。 这更接近您要求做的事情,但我目前没有在我的代码中使用它。所以买家要当心.

。干杯。

        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader( "Content-Disposition", "attachment; filename=ProposalRequest-" + fileName + ".xslx" );
        Response.BinaryWrite( pck.GetAsByteArray() );
        // myMemoryStream.WriteTo(Response.OutputStream); //works too
        Response.Flush();
        Response.Close();

DougY 发布的答案可能很好用,但是在他发布之前我确实找到了解决方案。

我不会将此标记为已回答,因为我相信有更好的方法,如果有人想发布或评论最好的方法,请标记答案。

感谢您的回复 道格·

控制器的 2 种方法可能可以组合,但这就是它的结局。

控制器

public static string ContentType { get; set; }
public static string FilePath { get; set; }
public static string FileName { get; set; }
public static byte[] Bytes { get; set; }
public void ExportToExcel(int BatchID,string BatchName)//is called first to set the variables
    {
        string contentType;
        byte[] bytes;
        string ret = DataAccess.ExportUtility.CreateExcelFile(BatchID, BatchName,out contentType, out bytes);
        ContentType = contentType;
        Bytes = bytes;
        FileName = ret[1];


    }
    public ActionResult DownloadExcelFile()//is then called to download the file
    {
        return File(Bytes, ContentType, FileName);
    }

导出实用程序类

public static string[] CreateExcelFile(int batchid,string batchName,out string ContentType, out byte[] Bytes)
    {
        string fileName = batchName + " Reason_Code_Export.xlsx";
        var serverPath = HttpContext.Current.Server.MapPath("~/ExportFiles/");
        DirectoryInfo outputDir = new DirectoryInfo(serverPath);
        byte[] bytes;
        FileInfo newfile = new FileInfo(outputDir.FullName + fileName);
        if (newfile.Exists)
        {
            newfile.Delete();
            newfile = new FileInfo(outputDir.FullName + fileName);
        }
        Dictionary<string,int> MAData = PolicyDataAccess.GetMatchActionData(batchid);
        MemoryStream MS = new MemoryStream();
        ExcelPackage package;
        using (package = new ExcelPackage(newfile))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(batchName);
            worksheet.Cells["A1"].Value = batchName + " Reason_Code_Export";
            worksheet.Cells["A1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells["A1:B1"].Merge = true;
            worksheet.Cells["A1:B1"].Style.Font.Bold = true;
            worksheet.Cells["A2"].Value = "Reason Code";
            worksheet.Cells["B2"].Value = "Number of Reason Codes Selected";
            worksheet.Cells["A2:B2"].Style.Font.Bold = true;
            int row = 3;
            int col = 1;
            foreach (KeyValuePair<string,int> MA in MAData)
            {
                worksheet.Cells[row, col].Value = MA.Key;
                worksheet.Cells[row, col + 1].Value = MA.Value;
                row++;
            }
            worksheet.Column(1).Width = 34.29;
            worksheet.Column(2).Width = 34.29;
            package.Workbook.Properties.Title = batchName + " Reason_Code_Export";
            package.Workbook.Properties.Author = "Intranet Application: Unclaimed Properties";
            package.Workbook.Properties.Company = "Assurity Life 2013";
            Bytes = package.GetAsByteArray();
            //package.SaveAs(newfile);//MS);
        }
        MS.Position = 0;
        var rl = serverPath + fileName;
        var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        ContentType = contentType;
        FileStreamResult FSR = new FileStreamResult(MS, contentType);
        FSR.FileDownloadName = fileName;
        string[] ret = new string[2];
        ret[0] = serverPath;
        ret[1] = fileName;

        return ret;
    }