I created a code in c# which creates and saves excel file. The code can successfully create and save excel file, but when I open the excel file created, it displays a warning message telling:
The file format and extension of 'filename.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
I am using the following code:
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();
}
}
What should I do to avoid receiving that warning message?
If you see the 'File Format and Extension of Don't Match' error, the Excel file you are trying unsuccessfully to open is likely in fact of a different extension that the one that is currently hardwired.
To change a file extension on Windows or macOS, just click on the file and edit the last three or four letters to show the correct extension for the format. Modifying the extension doesn't actually change any of the file's contents, but it can help your applications recognize the file, thus helping you open it.
I know this problem may be resolved by now, but just trying to help you without modifying the code can still use .xls format in your's and suppress this warning while opening the file by setting a registry.
Open reg edit, navigate to HKEY_CURRENT_USER\Software\Microsoft\Office\14\Excel\Security
Create a DWord
with name ExtensionHardening
and set the value to 0.
This might get your system vulnerable, but it is not a big deal when working in organisation network, at-least when you're sure of downloading the type of doc and source.
Just change the .xls to .xlsx if you have the latest office installed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With