C# 生成的 Excel 文件:文件格式或文件扩展名无效

C# Generated Excel File: File Format or File Extension is not valid

我正在调用操作 "Export",我在其中传递视图模型列表并定义格式

public ActionResult DownloadTokenlist(string startDate = null, string endDate = null)
            {        
                using (HRCTSStatisticDb db = new HRCTSStatisticDb(Setting.ClientId))
                {    
                    List<TokenExportViewModel> tokenExportViewModels = new List<TokenExportViewModel>();

                    Response.AddHeader("content-disposition", $"attachment;filename=Tokenlist_{DateTime.Now.ToString("dd.MM.yyyy")}.xlsx");
                    log.InfoFormat($"The {new HomeController().UserRole(Context.LoggedInUser)}: {Context.LoggedInUser} has used the exceldownload");

                    return File(new ExcelExport().Export(tokenExportViewModels), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                }
            }

我调用的操作(ExcelEngine 由 Syncfusion 提供):

public MemoryStream Export(List<TokenExportViewModel> list)
    {
        MemoryStream stream = new MemoryStream();
        using (ExcelEngine excelEngine = new ExcelEngine())
        {
            IApplication application = excelEngine.Excel;
            application.DefaultVersion = ExcelVersion.Excel2010;
            IWorkbook workbook = application.Workbooks.Create(1);
            IWorksheet worksheet = workbook.Worksheets.Create("Tokenlist");

            IStyle defaultStyle = workbook.Styles.Add("default");
            defaultStyle.Font.Size = 12;

            worksheet.SetDefaultColumnStyle(1, 20, defaultStyle);
            worksheet.SetDefaultRowStyle(1, 300, defaultStyle);

            worksheet.UsedRange.AutofitColumns();
            worksheet.Range["A1"].Text = $"Tokenlist - {DateTime.Today.ToString("dd.MM.yyyy")}";
            worksheet.Range["A1"].CellStyle = h1Style;
            workbook.SaveAs(stream);
            workbook.Close();
        }
        return stream;
    }

我只发布了对文件有影响的代码,并且(可能)会产生错误。 没有错误,直到我打开文件,然后弹出这个异常:

Excel cannot open the file 'Tokenlist_22.05.2018.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

我已尝试将文件格式更改为 .xls 和 .vbs,但均无效。使用 .xls 我可以打开文档,但里面没有数据。

.close() 没有太大变化,它只是关闭了之前打开的输出流。

使用 FileContentResult Overload,您可以在其中提供 fileDownloadName,如下所示:

return File(excelExport.Export(tokenExportViewModels).ToArray(),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Tokenlist_{DateTime.Now.ToString("dd.MM.yyyy")}.xlsx");

并使用流 ToArray() 扩展到 return byte[]

(我假设您的 Export 方法正在生成有效文档)

由于流在返回时到达结束位置,下载的文件已损坏。因此,建议将其当前位置设置为 0 来解决此问题。请参考下面的代码来实现相同的目的。

代码示例:

            workbook.SaveAs(stream);
            workbook.Close();
            stream.Position = 0;

我们还分享了一个简单的示例供您参考,可以从以下链接下载link。

示例 Link:http://www.syncfusion.com/downloads/support/directtrac/general/ze/Sample1020485770.zip

我为 Syncfusion 工作。