Download file with ClosedXML

前端 未结 7 2226
走了就别回头了
走了就别回头了 2020-12-03 04:46

All

How can I download a file so the user sees that it is downloading (like with a stream?)

I am currently using ClosedXML, but if I use the SaveAs method, I

7条回答
  •  盖世英雄少女心
    2020-12-03 05:14

    The SaveAs() method supports stream, so to get the ClosedXml workbook as a stream I use:

    public Stream GetStream(XLWorkbook excelWorkbook)
    {
        Stream fs = new MemoryStream();
        excelWorkbook.SaveAs(fs);
        fs.Position = 0;
        return fs;
    }
    

    And then for downloading the file:

    string myName = Server.UrlEncode(ReportName + "_" + DateTime.Now.ToShortDateString() + ".xlsx");
    MemoryStream stream = GetStream(ExcelWorkbook);
    
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=" + myName);
    Response.ContentType = "application/vnd.ms-excel";
    Response.BinaryWrite(stream.ToArray());
    Response.End();
    

提交回复
热议问题