3

我通过使用 EPPlus 在服务器上生成了一个 Excel 文件,该文件是正确制作的,并且使用 window.location 在本地计算机上工作正常,但在部署到服务器时什么也不做。我正在尝试通过 MVC 控制器返回 FileStreamResult,但我认为它不起作用。我正在使用 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;
    }

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

4

3 回答 3

6

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

设置 excel 表后,无需保存或将其添加到 MemoryStream,只需将字节数组设置为packge.GetAsByteArray()并从您的操作中将其作为 File 而不是 FileStreamResult返回。

var FileBytesArray = packge.GetAsByteArray();
return File(FileBytesArray, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename + ".xlsx");
于 2017-03-09T05:01:19.647 回答
1

    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();
于 2013-10-10T18:25:15.473 回答
-1

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

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

感谢道格的回复

控制器的两种方法可能可以组合,但这就是它最终的结果。

控制器

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);

    }

ExportUtility 类

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;
    }
于 2013-10-11T18:13:24.943 回答