سؤال

So I'm using the fancy EPPlus library to write an Excel file and output it to the user to download. For the following method I'm just using some test data to minimize on the code, then I'll add the code I'm using to connect to database later. Now I can download a file all fine, but when I go to open the file, Excel complains that it's not a valid file and might be corrupted. When I go to look at the file, it says it's 0KB big. So my question is, where am I going wrong? I'm assuming it's with the MemoryStream. Haven't done much work with streams before so I'm not exactly sure what to use here. Any help would be appreciated!

[Authorize]
public ActionResult Download_PERS936AB()
{
    ExcelPackage pck = new ExcelPackage();
    var ws = pck.Workbook.Worksheets.Add("Sample1");

    ws.Cells["A1"].Value = "Sample 1";
    ws.Cells["A1"].Style.Font.Bold = true;
    var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
    shape.SetPosition(50, 200);
    shape.SetSize(200, 100);
    shape.Text = "Sample 1 text text text";

    var memorystream = new MemoryStream();
    pck.SaveAs(memorystream);
    return new FileStreamResult(memorystream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "PERS936AB.xlsx" };
}
هل كانت مفيدة؟

المحلول

Here's what I'm using - I've been using this for several months now and haven't had an issue:

public ActionResult ChargeSummaryData(ChargeSummaryRptParams rptParams)
{
    var fileDownloadName = "sample.xlsx";
    var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    var package = CreatePivotTable(rptParams);

    var fileStream = new MemoryStream();
    package.SaveAs(fileStream);
    fileStream.Position = 0;

    var fsr = new FileStreamResult(fileStream, contentType);
    fsr.FileDownloadName = fileDownloadName;

    return fsr;
}

One thing I noticed right off the bat is that you don't reset your file stream position back to 0.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top