如何修复文件格式和扩展名不匹配?

我在c#中创build了一个用于创build和保存excel文件的代码。 代码可以成功创build和保存excel文件,但是当我打开创build的excel文件时,会显示一条警告消息,告诉“filename.xls的文件格式和扩展名”不匹配,文件可能被损坏或不安全。除非你信任它的来源,否则不要打开它,你想打开吗?“ 我正在使用下面的代码:

private void button1_Click(object sender, EventArgs e) { saveFileDialogSummary.Filter = "Excel Flie|*.xls"; saveFileDialogSummary.FilterIndex = 0; saveFileDialogSummary.RestoreDirectory = true; saveFileDialogSummary.CreatePrompt = true; saveFileDialogSummary.Title = "Export Excel File To"; Excel.Application ExcelApp = new Excel.Application(); ExcelApp.Application.Workbooks.Add(Type.Missing); ExcelApp.Columns.ColumnWidth = 30; for (int i = 0; i < dataGridViewSummary.Rows.Count; i++) { DataGridViewRow row = dataGridViewSummary.Rows[i]; for (int j = 0; j < row.Cells.Count; j++) { ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString(); } } DialogResult res = saveFileDialogSummary.ShowDialog(); if(res == DialogResult.OK){ ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialogSummary.FileName); ExcelApp.ActiveWorkbook.Saved = true; ExcelApp.Quit(); } } 

我应该怎么做才能避免收到警告信息?

如果您安装了最新的办公室,请将.xls更改为.xlsx。

我知道现在可以解决这个问题,但只是试图帮助你而不修改代码仍然可以使用.xls格式在你的和压制这个警告,同时通过设置registry打开文件。 打开注册编辑,导航到HKEY_CURRENT_USER\Software\Microsoft\Office\14\Excel\Security

创build名称为ExtensionHardeningDWord ,并将该值设置为0。

这可能会让你的系统容易受到攻击,但是在组织networking中工作并不是什么大不了的事,至less当你确定要下载文档types和源代码的时候。

“文件格式和扩展名不匹配”的解决scheme是closures工作簿**($ workbook-> close;)**,最后在对文件进行所有必要的写入之后。

我从邮件中打开“XLS”文件时遇到同样的问题。 我创build了一个文件,并插入了我的所有东西初始化,并没有closures我发送邮件作为附件的工作簿。 后来我意识到必须closures工作簿并作为附件发送。

文件扩展名.xls和.xlsx文件包含不同的布局。 扩展名.xls在版本2003中使用,然后使用版本.xlsx扩展名。
您必须将excel文件导出为.xlsx格式。 它将支持所有版本,因为我用过。

将DLLS添加到bin文件夹中
1. ClosedXML.dll
2. DocumentFormat.OpenXml.dll

要导出到.xlsx的代码

  DataTable dt = new DataTable(); //Create column and inser rows using (XLWorkbook wb = new XLWorkbook()) { var ws = wb.Worksheets.Add(dt, Sheetname); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = ""; HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + p_FileName + ".xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } }