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

夙愿已清 提交于 2020-01-14 05:42:07

问题


I'm calling the action "Export" where i pass a list of viewmodels and define the format

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");
                }
            }

The action i call (ExcelEngine is by 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;
    }

I only posted the code which has an impact on the file and (maybe) could create the error. There is no error, until i open the file, then this exception pops up:

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.

I've tried to change the file format to .xls and .vbs but neither works. With .xls I can open the document but then it has no data in it.

The .close() doesn't change much, it just closes the output stream previously opened.


回答1:


Use the FileContentResult Overload where you can provide thefileDownloadName like this:

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

And use the stream ToArray() extension to return a byte[].

(I assume your Export method is generating a valid document)




回答2:


As stream reached end position while returning it, the downloaded file is getting corrupted. So, it is recommended to set its current position to 0 to resolve this issue. Please refer below code to achieve the same.

Code Example:

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

We have also shared a simple sample for your reference which can be downloaded from following link.

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

I work for Syncfusion.



来源:https://stackoverflow.com/questions/50468273/c-sharp-generated-excel-file-file-format-or-file-extension-is-not-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!