Vivendi
Vivendi

Reputation: 21097

Force download of a stream - force download excel file

I'm creating an excel file in memory using the MemoryStream API and EPPlus for creating an excel document.

My code for creating an excel file basically looks like this:

public Stream GetXlsDocument(IQueryable data)
{

    const string sheetName = "Sheet1";
    var file = new FileInfo("test2.xls");

    MemoryStream stream = new MemoryStream();
    using (ExcelPackage p = new ExcelPackage(stream))
    {
        p.Workbook.Worksheets.Add(sheetName);

        ExcelWorksheet ws = p.Workbook.Worksheets[1];
        ws.Name = sheetName;
        ws.Cells.Style.Font.Size = 11;
        ws.Cells.Style.Font.Name = "Calibri";

        // Headers
        ws.SetValue(1, 1, "Some data");

        p.SaveAs(stream);
    }

    stream.Position = 0;
    return stream;
}

Then my other function should serve this stream as a download to the user. I'm trying to do that like this:

var file = Documents.GetXlsDocument();

var memoryStream = new MemoryStream();
file.CopyTo(memoryStream);

Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=nfile.xls");
Response.BinaryWrite(memoryStream.ToArray());
Response.End();

This does show me a download dialog. But when i open my excel file, then the entire excel document is filled with garbage (i guess the binary data represented as a string).

I have no idea what i'm doing wrong.

Anyone any idea how i can make the excel file downloadable in a good format? Perhaps EPPlus already has something for this?

Upvotes: 1

Views: 4119

Answers (2)

w00
w00

Reputation: 26812

Don't add a stream in the constructor. Keep the constructor empty.

So change this line:

using (ExcelPackage p = new ExcelPackage(stream))

to this:

using (ExcelPackage p = new ExcelPackage())

Upvotes: 2

user1661538
user1661538

Reputation:

For the 'Response.ContentType' use application/octet-stream as the type. This will tell most browsers to treat the file as data it should download nothing else.

Upvotes: 0

Related Questions