在.net中使用EPPlus生成并下载.xlsx文件

问题描述 投票:0回答:1

我试图生成一个.xlsx文件并使用.net中的EPPlus包下载它。以下是我尝试过的代码。

using (var package = new OfficeOpenXml.ExcelPackage())
            {
                var workbook = package.Workbook;
                var worksheet = workbook.Worksheets.Add("SampleData");

                // Adding header
                worksheet.Cells[1, 1].Value = "Data1";
                worksheet.Cells[1, 2].Value = "Data2";
                worksheet.Cells[1, 3].Value = "Data3";
                worksheet.Cells[1, 4].Value = "Data4";
                worksheet.Cells[1, 5].Value = "Data5";
                worksheet.Cells[1, 6].Value = "Data6";

                // Save to a memory stream
                using (var stream = new MemoryStream())
                {
                    package.SaveAs(stream);

                    // Reset stream position
                    stream.Position = 0;

                    // Set HTTP Response
                    
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8";
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=SampleData.xlsx");
                    HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                    HttpContext.Current.Response.End();
                }
            }

文件正在下载。但是当在 Excel 中打开它时,它显示以下错误。

“Excel 无法打开文件“SampleData.xlsx”,因为文件格式或文件扩展名无效。请验证文件是否已损坏且文件扩展名与文件格式匹配”

这可能是什么原因?

谢谢

c# .net excel xlsx epplus
1个回答
0
投票

我可以清楚地看到它造成麻烦的一个原因是保存文件后需要进行流刷新。

通常处理文件涉及内存流,当您将一些数据写入该流时,在保存文件之前该流可能不会被刷新。

要解决此问题,您可以尝试添加

stream.Flush();
就在
package.SaveAs(stream)
线之后。

所以你的整个代码如下所示:

using (var package = new OfficeOpenXml.ExcelPackage())
{
   var workbook = package.Workbook;
   var worksheet = workbook.Worksheets.Add("SampleData");

   // Adding header
   worksheet.Cells[1, 1].Value = "Data1";
   worksheet.Cells[1, 2].Value = "Data2";
   worksheet.Cells[1, 3].Value = "Data3";
   worksheet.Cells[1, 4].Value = "Data4";
   worksheet.Cells[1, 5].Value = "Data5";
   worksheet.Cells[1, 6].Value = "Data6";

   // Save to a memory stream
   using (var stream = new MemoryStream())
   {
       package.SaveAs(stream);

       stream.Flush(); // this needs to be added

       stream.Position = 0;

       // Set HTTP Response
       HttpContext.Current.Response.Clear();
       HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
       HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=SampleData.xlsx");
       HttpContext.Current.Response.BinaryWrite(stream.ToArray());
       HttpContext.Current.Response.End();
    }
}

这将解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.