0

can not open excel file in c# because The file you are trying to open in a different format than specified file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

  private void button1_Click(object sender, EventArgs e)
        {
            string fileName = Directory.GetCurrentDirectory();
            fileName += "\\" + textBox1.Text + ".xls";

            var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
            var conn = new OleDbConnection(connectionString);
            conn.Open();

            var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            var cmd = conn.CreateCommand();

            ///////////////////////     sheet 1
            cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
            var adapter = new OleDbDataAdapter(cmd);
            var ds = new DataSet();
            adapter.Fill(ds);
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
        }
Damith
  • 62,401
  • 13
  • 102
  • 153
Hossein
  • 439
  • 3
  • 9
  • Show your code and tell people what have you tried so far.. Please also read [FAQ] and [ask] – Soner Gönül Apr 15 '13 at 05:50
  • Have you looked at this: http://stackoverflow.com/questions/652377/excel-spreadsheet-generation-results-in-different-file-format-than-extension-er?rq=1 ? – David Tansey Apr 15 '13 at 05:52

1 Answers1

0

This is because the file is actually basically just a CSV file with an XLS extension to make it open in Excel.

it happens in new versions of Excel. Older ones will happily export them.

See this Microsoft doc for more information:

http://support.microsoft.com/kb/948615

One option is simply to rename the file name to .csv, and keep the user interface as saying that it is an Excel file (Excel is quite happy to read csv files). Given that Windows tends to hide the file extension, this seems like a fairly attractive option.

EDIT

"External table is not in the expected format." typically occurs when trying to use an Excel 2007 file with a connection string that uses: Microsoft.Jet.OLEDB.4.0 and Extended Properties=Excel 8.0

Go through:

Excel "External table is not in the expected format."

Hope its helpful.

Community
  • 1
  • 1
Freelancer
  • 9,008
  • 7
  • 42
  • 81