打开下载的excel文件后文件格式错误

在我的应用程序中,我试图从mvc中的字节数组内容下载excel文件。 文件下载后,当我打开下载的文件,我得到错误。

“您试图打开的文件”XXXX.xls“采用与文件扩展名指定的格式不同的格式。在打开文件之前,确认文件没有损坏,并且来自受信任的来源。档案现在?“

在上面的错误中点击是,我得到另一个错误

Excel在'XXXX.xls'中发现了不可读的内容。 你想恢复这个工作簿的内容? 如果您信任此工作簿的来源,请单击“是”。

再次,当我在上面的错误消息中点击yes时,我又收到第一个错误消息。

“您试图打开的文件”XXXX.xls“采用与文件扩展名指定的格式不同的格式。在打开文件之前,确认文件没有损坏,并且来自受信任的来源。档案现在?“

在上面的错误消息中点击yes后,excel打开一个修复popup窗口,显示里面的消息。 消息是

修复logging:从/xl/styles.xml部分格式(样式)

这是我的控制器代码

[HttpPost, FileDownload] public FileContentResult GetReport(DateTime StartDate, DateTime EndDate, int ReportType) { var reportData = new Model().GetReport(StartDate, EndDate, ReportType); string fileName = "Report " + (TimeZoneUtil.ConvertUtcDateTimeToESTDateTime(DateTime.UtcNow).ToString("yyyy:MM:dd:hh:mm:ss")) + ".xls"; return File(reportData, MimeMapping.GetMimeMapping(fileName), fileName); } 

我使用jQuery File Download Plugin调用这个方法,我的代码是

  var dataToSend = { "StartDate": $("#dtpreportstartdate").val(), "EndDate": $("#dtpreportenddate").val(), "ReportType": value }; $.fileDownload(GetBaseUrl() + "Dashboard/GetReport", { preparingMessageHtml: "success message", failMessageHtml: "Error message", httpMethod: "POST", data: dataToSend }); 

以下是我获得excel内容的方法

  public byte[] CreateReportFile(List<BGClass> BGRows) { MemoryStream ms = new MemoryStream(); SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook); WorkbookPart wbp = xl.AddWorkbookPart(); WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>(); Workbook wb = new Workbook(); FileVersion fv = new FileVersion(); fv.ApplicationName = "Microsoft Office Excel"; Worksheet ws = new Worksheet(); SheetData sd = new SheetData(); AddStyleSheet(ref xl); Row headerRow = new Row(); Cell CreatedDateHeaderCell = new Cell() { StyleIndex = Convert.ToUInt32(1) }; CreatedDateHeaderCell.DataType = CellValues.String; CreatedDateHeaderCell.CellValue = new CellValue("Created Date"); headerRow.Append(CreatedDateHeaderCell); Cell BackgroundNameHeaderCell = new Cell() { StyleIndex = Convert.ToUInt32(1) }; BackgroundNameHeaderCell.DataType = CellValues.String; BackgroundNameHeaderCell.CellValue = new CellValue("Bg Name"); headerRow.Append(BackgroundNameHeaderCell); sd.Append(headerRow); foreach (BGClass reportRow in BGRows) { Row dataRow = new Row(); Cell CreatedDateDataCell = new Cell(); CreatedDateDataCell.DataType = CellValues.String; CreatedDateDataCell.CellValue = new CellValue(TimeZoneHelper.ConvertUtcDateTimeToESTDateTime(reportRow.CreatedDate).ToString()); dataRow.Append(CreatedDateDataCell); Cell BackgroundNameDataCell = new Cell(); BackgroundNameDataCell.DataType = CellValues.String; BackgroundNameDataCell.CellValue = new CellValue(reportRow.BackgroundName); dataRow.Append(BackgroundNameDataCell); } ws.Append(sd); wsp.Worksheet = ws; wsp.Worksheet.Save(); Sheets sheets = new Sheets(); Sheet sheet = new Sheet(); sheet.Name = "Report"; sheet.SheetId = 1; sheet.Id = wbp.GetIdOfPart(wsp); sheets.Append(sheet); wb.Append(fv); wb.Append(sheets); xl.WorkbookPart.Workbook = wb; xl.WorkbookPart.Workbook.Save(); xl.Close(); return ms.ToArray(); } 

代码有什么问题? 为什么我打开文件时出现excel错误? 我尝试了很多博客来改变MIMEtypes,但没有为我工作。 任何想法?

您正在使用OpenXML SDK中的SpreadsheetDocument.Create()

这表明您正在编写XLSX文件,但是您使用XLS扩展名和MIMEtypes来提供文件。

将文件扩展名更改为.xlsx ,指示XML格式。

我能提出一些build议吗?

为什么不使用免费的C#库,就像我的(下面的链接),你可以传递你的List<>variables,它会为你创build一个完美的.xlsx文件。

CodeProject:导出到Excel,在C#

一行代码,这个问题就消失了:

 public void CreateReportFile(List<BGClass> BGRows) { CreateExcelFile.CreateExcelDocument(BGRows, "SomeFilename.xlsx"); } 

所有的C#源代码都是免费提供的。

我做了一些研究后解决了这个问题。 我使用函数AddStyleSheet(ref xl);将样式应用于Excel中的标题行AddStyleSheet(ref xl); 。 在该方法中发生问题时,我将样式应用于单元时缺lessless量参数。

我的老方法是

 private WorkbookStylesPart AddStyleSheet(ref SpreadsheetDocument spreadsheet) { WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>(); Stylesheet workbookstylesheet = new Stylesheet(); Font fontBold = new Font(new FontName() { Val = "Arial" }); // Default font Font defaultFont = new Font(new FontName() { Val = "Arial" }); // Bold font Bold bold = new Bold(); defaultFont.Append(bold); Fonts fonts = new Fonts(); // <APENDING Fonts> fonts.Append(fontBold); fonts.Append(defaultFont); //// <Fills> //Fill fill0 = new Fill(); // Default fill //Fills fills = new Fills(); // <APENDING Fills> //fills.Append(fill0); // <Borders> //Border border0 = new Border(); // Defualt border //Borders borders = new Borders(); // <APENDING Borders> //borders.Append(border0); // <CellFormats> CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }; // Default style : Mandatory | Style ID =0 CellFormat cellformat1 = new CellFormat() { FontId = 1 }; // Style with Bold text ; Style ID = 1 // <APENDING CellFormats> CellFormats cellformats = new CellFormats(); cellformats.Append(cellformat0); cellformats.Append(cellformat1); // Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER> workbookstylesheet.Append(fonts); //workbookstylesheet.Append(fills); //workbookstylesheet.Append(borders); workbookstylesheet.Append(cellformats); // Finalize stylesheet.Stylesheet = workbookstylesheet; stylesheet.Stylesheet.Save(); return stylesheet; } 

在这个函数中,我评论了填充和边框部分,因为我不需要它。 但是,如果您在应用样式索引时不使用它,则会给您提供“无法访问的内容”错误,这是我所面对的。

所以我改变了我的方法,并添加填充和边框部分风格。 这是我更新的方法。

  private WorkbookStylesPart AddStyleSheet(ref SpreadsheetDocument spreadsheet) { WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>(); Stylesheet workbookstylesheet = new Stylesheet( new Fonts( new Font( // Index 0 – The default font. new FontSize() { Val = 11 }, new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }, new FontName() { Val = "Arial" }), new Font( // Index 1 – The bold font. new Bold(), new FontSize() { Val = 11 }, new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }, new FontName() { Val = "Arial" }) ), new Fills( new Fill( // Index 0 – The default fill. new PatternFill() { PatternType = PatternValues.None }) ), new Borders( new Border( // Index 0 – The default border. new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder()) ), new CellFormats( new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }, // Index 0 – The default cell style. If a cell does not have a style index applied it will use this style combination instead new CellFormat() { FontId = 1, FillId = 0, BorderId = 0 } // Index 1 – Bold ) ); stylesheet.Stylesheet = workbookstylesheet; stylesheet.Stylesheet.Save(); return stylesheet; } 

对于ref链接https://blogs.msdn.microsoft.com/chrisquon/2009/11/30/stylizing-your-excel-worksheets-with-open-xml-2-0/