如何在MVC中使用EPPlus从服务器下载.xlsx文件

时间:2013-10-04 19:19:27

标签: c# asp.net-mvc excel download epplus

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

我一直在寻找ASP.NET MVC EPPlus Download Excel File来获取我的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;
    }

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

3 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

EPPLUS给了我一些真正的麻烦。
 我对MVC并不熟悉,但我认为你想要直接写输出响应。在这种情况下,我会使用类似下面的内容   我看到我在评论中留下了内存流写入的工作原理。这更接近你要求做的,但我目前没有在我的代码中使用它。所以买家要小心。

  .cheers。

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

答案 2 :(得分:-1)

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

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

感谢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;
    }