Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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" };
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
931 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...