Reading .xls (97-2003) files with ACE after oppening them with Excel 2013 - c#

We have been using Access Database Engine 2010 (V.14.0.4763.1000) for reading Excel (97-2003) .xls files from c# (.Net framework 4.0) with succesful results for a really long time. But now, after opening the files with Excel 2013, and saving them again in the same format (97-2003 .xls) we can't read the files anymore.
It gives us the following error:
External table is not in the expected format.
This doesn't happen when we open and save the files with Excel 2007 or 2010, only with 2013. We use the following connection string for reading the file:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;HDR=YES
where {0} is replaced by the file name and path. It seems Excel 2013 corrupts the 97-2003 file structure in some way that ACE doesn't understand. Is there any way we can fix this issue?
Just to be clear, the file format we need to read is always .xls (97-2003), we don't want to read .xlsx files (we can do this with no problem), but we need to use (97-2003) for compatibility with other systems.
Edit:
I made a very simple test program to illustrate, you can get it here:
https://www.dropbox.com/s/1ftw3emilnbuw6t/ExcelTest.rar
The .rar file contains:
ExcelReadingTest.exe (The Program)
Program.cs (The source code)
SavedFromExcel2007.xls (An example Excel file saved from Excel 2007 in 97-2003 format)
SavedFromExcel2013.xls (The same Excel file saved from Excel 2013 in 97-2003 format)
To run the example save all files in c:\temp and type on a cmd console:
C:\>cd c:\temp (Enter)
C:\temp>ExcelReadingTest SavedFromExcel2007.xls (Enter)
You´ll get:
1 Hello
2 World
3 Reading
4 Excel
Press Enter...
And if you type:
C:\temp>ExcelReadingTest SavedFromExcel2013.xls (Enter)
You´ll get this with Access Database Engine 2007 (12.0.6612.1000) installed:
System.Data.OleDb.OleDbException (0x80040E37): The Microsoft Access database eng
ine could not find the object 'Sheet1$'. Make sure the object exists and that yo
u spell its name and the path name correctly. If 'Sheet1$' is not a local object
, check your network connection or contact the server administrator.
en System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResul
t hr)
en System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARA
MS dbParams, Object& executeResult)
en System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
en System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Ob
ject& executeResult)
en System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behav
ior, String method)
en System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
en System.Data.OleDb.OleDbCommand.ExecuteReader()
en ExcelReadingTest.Program.Main(String[] args)
Press Enter...
Or you´ll get this with Access Database Engine 2010 (14.0.7015.1000) installed:
System.Data.OleDb.OleDbException (0x80004005): External table is not in the expe
cted format.
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString cons
tr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOpti
ons options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection o
wningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbC
onnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection ow
ningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection ou
terConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at ExcelReadingTest.Program.Main(String[] args) in c:\users\ivanm\documents\v
isual studio 2010\Projects\ExcelReadingTest\ExcelReadingTest\Program.cs:line 41
Press Enter...

Related

COM class factory Error in Microsoft.Office.Interop [duplicate]

I am trying to convert a .xls file to an .xlsx file on the server-side using Microsoft.Office.Interop.Excel.Workbook class as follows:
workBook.SaveAs("FILENAME_HERE", XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
and I get the following error:
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)). : System.Runtime.InteropServices.COMException (0x80080005): Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at CALLING_METHOD_IN_MY_LIBRARY_HERE...
The problem is that this error occurs only on the staging server; on my local machine it works fine.
Things that I have tried on the staging server:
**1) Run dcomcnfg open Component Services
2) Expand Component Services "->" Computer "->" My Computer "->" the DCOM configuration "
3) Find the "Microsoft Excel application."
4) Right to open the Properties dialog box
5) Clicked on the "Security" tab,
6) "Launch and Activation Permissions, configure permissions, have added permissions - Identity run under Adminstrator user (This User), Interactive User and Launching Users
7). Launch and activation permissions + Access Permissions + Configuration Permissions => added IIS_IUSRS + Network Service with Full Controll**
2.
Changed the build of the project that converts the .xls file from "Any CPU" to "x86" on my local machine and published this library on the server.
Did someone figured out how to fix this problem? I am struggling on fix this issue for 2 days now.
Using DCOMCNFG.exe. Open it and go to:
Component Services -> Computers -> My Computer -> DCOM Config -> Microsoft Excel Application.
Open the properties, select Identity tab and select the interactive user.
I found the solution elsewhere.
Doing the following did solve my problem:
Using DCOMCNFG.exe. Open it and go to: Component Services -> Computers -> My Computer -> DCOM Config -> Microsoft Excel Application. Open the properties, select Identity tab and select the interactive user.
BUT - the problem came back every few minutes !
After hours of trying to figure out the cause, I noticed my server had hundreds of opened WINWORD.EXE processes. This caused a memory issue which leaded to the exception from hresult 0x80080005 error.
Well, stupidly enough, I forgot to write the code to close the interop application. Once I fixed that, the error was gone.
doc.Close(false);
Marshal.ReleaseComObject(doc);
word.Quit();
Marshal.ReleaseComObject(word);
I found this article which talks more about this issue in depth If this helps,
error “80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE))” could occur due to following reasons:
The machine has a high CPU load and the process takes a long time to
start and fails to execute the CoRegisterClassObjects() in less than
120 seconds.
The COM server doesn't register for the right class IDs.
The COM server is currently stopping and there is a race condition
between CoCreateInstance and the COM server stopping part.
There is a security problem in the way the COM server is started
(this page seems to suggest misspelled passwords or lacking the
"Login as Batch Job" privilege for "Run As.." COM servers, but
anyway I would suggest re-verifying this information for your
specific configuration)
https://blogs.msdn.microsoft.com/adioltean/2005/06/24/when-cocreateinstance-returns-0x80080005-co_e_server_exec_failure/
I fixed this issue with this solution:
right click on Component Services/Computers/DCOM Config/Microsoft Word97 - 2003 Document
properties/General Tab
set Authentication Level:None
TLDR; the fix for me is to disable AutoRecover from File -> Options -> Save,
then discard all autorecovered files. It would appear it's the volume of autorecover files which is the root cause.
Background
I cycle through a lot open / close /compute cycles. Periodically the C# app fails to open a workbook with the below error.
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
The app repeatedly throws this error and is stuck in this state until the AutoRecovered files are cleared from Excel.
Another symptom follows; when I try to open Excel app (as if to create a new workbook, not open an existing one), it takes a long time spinning cpu cycles. It opens eventually and there are tons of files listed in the Recovered files pane on the left.
I Close the pane using the button, all the files are then discarded. Re-opening Excel again after this procedure is near instant. The app runs fine again from hereon.
Same problem was solved for me by "allowing desktop interaction" for the service. (in tomcat6w config tool on Log On tab)
Start -> Run (Windows+R)
Type: dcomcnfg -32 (hit enter)
this should open Component Services
Expand Component Services, Computers, My Computer, DCOM Config
Scroll down to "Microsoft Excel Application"
Right Click, select properties, go to Security tab
Edit Access Permissions
Click Add
Type <Computer_Name>/IIS_IUSRS (or go to Locations, select computer name - if using domain, by default, it will search the domain and will not find IIS_IUSRS)
Make sure the check box for "Allow" is checked for "Local Access"
Click OK, Click OK again (no rebooting is necessary)
Windows Update will reset this ever single time
Try to add Thread.Sleep Method, such as Thread.Sleep(2000) for 2 seconds after workBook.open and workBook.SaveAs two methods. If your Excel file has a lot of formats, try to extend few more seconds.

Visual FoxPro OLEDB error: Invalid path or file name

We have Novell server and there Advantage Database Server 9.1 is installed and all other Xbase++ programs access DBF files from that location.
I want to access DBF files from C# asmx webservice.
Problem is if I use Visual FoxPro VFP OLEDB then it only works while running asmx webservice in Visual studio's Debug mode but when I publish it to IIS, it gives this error:
System.Data.OleDb.OleDbException: Invalid path or file name
First Attempt (with ADS OLEDB):
It works ONLY when DBF files are not opened by non-ADS program. If any Xbase++ program first opens DBF file then "Locking situation" occurs and I can't access DBF file.
ADS connection string:
string connectionString = string.Format(#"Provider=Advantage OLE DB Provider;data source={0}; Advantage Server Type=ADS_REMOTE_SERVER;SecurityMode=ADS_IGNORERIGHTS;TableType=ADS_CDX;Locking=ADS_COMPATIBLE_LOCKING;", folderPath);
Second Attempt (with VFP OLEDB):
Then I tried VFP OLEDB but it only works when I run asmx webservice from Visual Studio's Debug mode and does not work after deployment to IIS, when I publish webservice to IIS it gives this error:
System.Data.OleDb.OleDbException: Invalid path or file name.
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
VFP connection string:
string connectionString = string.Format(#"Provider=vfpoledb.1;data source={0}; TableType=vfp;", folderPath);

Gembox error when reading an .xls file from .xlsx file

I have an .xlsx file and I have changed the file extension to .xls and I am trying to read it using Gembox library. The problem is that when I am trying to read the file using GemboxExcel.LoadXls(fileName); method I get the following error:
Exception message: Analysis failed: Reading error: file is not a valid
OLE2 Compound File. Exception stack trace: System.Exception: Analysis
failed: Reading error: file is not a valid OLE2 Compound File. --->
GemBox.CompoundFileException: Reading error: file is not a valid OLE2
Compound File. at GemBox.ReadData.ReadHeader(BinaryReader br,
ArrayList& masterAllocationTable) at
GemBox.ReadData..ctor(Ole2CompoundFile ole2File, Stream inputStream)
at GemBox.Ole2CompoundFile.Load(Stream stream, Boolean loadOnDemand)
at GemBox.Spreadsheet.ExcelFile.ReadStreamHelper(ExcelFile excelFile,
Stream inputStream, Boolean readSummaryStreams, Byte[]& ss, Byte[]&
dss, Boolean readMacros, Byte[]& ctls, Byte[]& compObj, Ole2Storage&
mStorage, String fileName) at
GemBox.Spreadsheet.ExcelFile.LoadXls(String fileName, XlsOptions
xlsOptions
The problem is that if that if I save the file from Excel (Microsoft Excel -> Save As -> .xls file) and then I open the file in my program and use the GemboxExcel.LoadXls(fileName); method, it works correctly.
I have installed the Microsoft Office Compatibility Pack on my machine but it does not work.
Did someone came across this issue?
By changing files extension just by renaming it (for example from "Book1.xlsx" to "Book1.xls") you are not changing the content of this file nor the file format used in it.
You see these formats are very different, XLS is a binary based file format while XLSX is an XML based file format. I'm not sure why you want to rename it to an .XLS extension, but nevertheless now you have a file in which file format and extension don't match and you need to load it as an XLSX file (because it still is an XLSX file format).
ExcelFile file = new ExcelFile();
file.LoadXlsx("Book1.xls", XlsxOptions.None);
If you want to convert the XLSX file to an XLS file then try the following:
ExcelFile file = new ExcelFile();
file.LoadXlsx("Book1.xlsx", XlsxOptions.None);
file.SaveXls("Book1.xls");
This will have the same effect just as "Microsoft Excel -> Save As -> .xls file" action.

Cannot encrypt / decrypt SQLite database in .NET4

I am running Visual Studio 2010 on a Windows 7 x64. The app I'm writing is supposed to run on all platforms (AnyCPU). I'm able to encrypt/decrypt the database file if I'm using the System.Data.SQLite.dll either x86 version (sqlite-netFx40-static-binary-bundle-Win32-2010-1.0.77.0.zip) or x64 one (sqlite-netFx40-static-binary-bundle-x64-2010-1.0.77.0.zip).
I need my app to run on both platforms x86 and x64 (Any CPU project build setting). I've tried installing the ADO.NET 4.0 Provider (SQLite-1.0.67.1-vs2010-net4-setup.exe). I added the reference (right-click on project, Add Reference, .NET tab -> System.Data.SQLite) and ran the program. If I decrypt the file and try to encrypt by calling ChangePassword("myPass"), I get the following exception:
System.EntryPointNotFoundException was caught
Message=Unable to find an entry point named 'sqlite3_rekey' in DLL 'System.Data.SQLite.DLL'.
Source=System.Data.SQLite TypeName=""
StackTrace:
at System.Data.SQLite.UnsafeNativeMethods.sqlite3_rekey(IntPtr db, Byte[ key, Int32 keylen)
at System.Data.SQLite.SQLite3.ChangePassword(Byte[ newPasswordBytes)
at System.Data.SQLite.SQLiteConnection.ChangePassword(Byte[ newPassword)
at System.Data.SQLite.SQLiteConnection.ChangePassword(String newPassword)
at SQLiteTest.Database.Encrypt() in C:\SQLiteTest\Database.cs:line 166
Also, I've tried to open a connection using the SQLiteConnection object and I get two different exceptions in two different cases.
First, if the file is encrypted and I don't specify a password in the connection string I get this:
System.Data.SQLite.SQLiteException was caught
Message=File opened
that is not a database file file is encrypted or is not a database
Source=System.Data.SQLite ErrorCode=-2147467259
StackTrace:
at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous,
UInt32 timeoutMS, String& strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior
behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
at System.Data.SQLite.SQLiteConnection.Open()
at SQLiteTest.Database.GetAllLanguages() in C:\SQLiteTest\Database.cs:line 216
Second, if I add the password parameter to the connection string, I get the System.EntryPointNotFoundException like the one above.
So, does anyone know a sure-fire way to work with encrypted SQLite database in a C# app on AnyCPU platform?
Thanks in advance!
Following Solution is a little bit dirty, but it may work, we didn't use encrypted database so i'm not 100% if that will work for you.
We downloaded both versions of sqlite dlls for x64 and x86 and placed them in different folders. We load them manually dependent on what platform application is currently running ( we check IntPtr.Size , from .net 4 there is a property in Environment class called Is64BitOperatingSystem) when we loaded assembly manually we get connection instance with
var sqliteConnectionType = assembly.GetType("System.Data.SQLite.SQLiteConnection");
(DbConnection)Activator.CreateInstance(sqliteConnectionType);
we don't use reference to any version of sqlite in our project.

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

I'm trying to read an Excel (xlsx) file using the code shown below. I get an "External table is not in the expected format." error unless I have the file already open in Excel. In other words, I have to open the file in Excel first before I can read if from my C# program. The xlsx file is on a share on our network. How can I read the file without having to open it first?
Thanks
string sql = "SELECT * FROM [Sheet1$]";
string excelConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathname + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
using (OleDbDataAdapter adaptor = new OleDbDataAdapter(sql, excelConnection)) {
DataSet ds = new DataSet();
adaptor.Fill(ds);
}
"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
Using the following connection string seems to fix most problems.
public static string path = #"C:\src\RedirectApplication\RedirectApplication\301s.xlsx";
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
Thanks for this code :) I really appreciate it. Works for me.
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
So if you have diff version of Excel file, get the file name, if its extension is .xlsx, use this:
Private Const connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
and if it is .xls, use:
Private Const connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" + path + ";Extended Properties=""Excel 8.0;HDR=YES;"""
(I have too low reputation to comment, but this is comment on JoshCaba's entry, using the Ace-engine instead of Jet for Excel 2007)
If you don't have Ace installed/registered on your machine, you can get it at: https://www.microsoft.com/en-US/download/details.aspx?id=13255
It applies for Excel 2010 as well.
Just add my case. My xls file was created by a data export function from a website, the file extention is xls, it can be normally opened by MS Excel 2003. But both Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0 got an "External table is not in the expected format" exception.
Finally, the problem is, just as the exception said, "it's not in the expected format". Though it's extention name is xls, but when I open it with a text editor, it is actually a well-formed html file, all data are in a <table>, each <tr> is a row and each <td> is a cell. Then I think I can parse it in a html way.
I had the same problem. which as resolved using these steps:
1.) Click File
2.) Select "save as"
3.) Click on drop down (Save as type)
4.) Select Excel 97-2003 Workbook
5.) Click on Save button
I had this same issue(Using the ACE.OLEDB) and what resolved it for me was this link:
http://support.microsoft.com/kb/2459087
The gist of it is that installing multiple office versions and various office sdk's, assemblies, etc. had led to the ACEOleDB.dll reference in the registry pointing to the OFFICE12 folder instead of OFFICE14 in
C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL
From the link:
Alternatively, you can modify the registry key changing the dll path to match that of your Access version.
Access 2007 should use OFFICE12, Access 2010 - OFFICE14 and Access
2013 - OFFICE15
(OS: 64bit Office: 64bit) or (OS: 32bit Office: 32bit)
Key: HKCR\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\
Value Name: (Default)
Value Data: C:\Program Files\Common Files\Microsoft
Shared\OFFICE14\ACEOLEDB.DLL
(OS: 64bit Office: 32bit)
Key:
HKCR\Wow6432Node\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\
Value Name: (Default)
Value Data: C:\Program Files (x86)\Common Files\Microsoft
Shared\OFFICE14\ACEOLEDB.DLL
I have also seen this error when trying to use complex INDIRECT() formulas on the sheet that is being imported. I noticed this because this was the only difference between two workbooks where one was importing and the other wasn't. Both were 2007+ .XLSX files, and the 12.0 engine was installed.
I confirmed this was the issue by:
Making a copy of the file (still had the issue, so it wasn't some save-as difference)
Selecting all cells in the sheet with the Indirect formulas
Pasting as Values only
and the error disappeared.
I was getting errors with third party and Oledb reading of a XLSX workbook.
The issue appears to be a hidden worksheet that causes a error. Unhiding the worksheet enabled the workbook to import.
If the file is read-only, just remove it and it should work again.
I know this is a very old post, but I can give my contribution too, on how I managed to resolve this issue.
I also use "Microsoft.ACE.OLEDB.12.0" as a Provider.
When my code tried to read the XLSX file, it received the error "External table is not in the expected format."
However, when I kept the file open in Excel and then the code tried to read it ... it worked.
SOLUTION:
I use Office 365 with company documents and in my case, the solution was very simple, I just needed to disable the sensitivity of the document, setting it to "public".
Detail: Even after saving as "public" the green check still remained marked in "Internal Use", but the problem remained solved after that.
I had this problem and changing Extended Properties to HTML Import fixed it as per this post by Marcus Miris:
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & importedFilePathAndName _
& ";Extended Properties=""HTML Import;HDR=No;IMEX=1"";"
ACE has Superceded JET
Ace Supports all Previous versions of Office
This Code works well!
OleDbConnection MyConnection;
DataSet DtSet;
OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\\Book.xlsx;Extended Properties=Excel 12.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
Ran into the same issue and found this thread. None of the suggestions above helped except for #Smith's comment to the accepted answer on Apr 17 '13.
The background of my issue is close enough to #zhiyazw's - basically trying to set an exported Excel file (SSRS in my case) as the data source in the dtsx package. All I did, after some tinkering around, was renaming the worksheet. It doesn't have to be lowercase as #Smith has suggested.
I suppose ACE OLEDB expects the Excel file to follow a certain XML structure but somehow Reporting Services is not aware of that.
the file might be locked by another process, you need to copy it then load it as it says in this post
This can also be a file that contains images or charts, see this: http://kb.tableausoftware.com/articles/knowledgebase/resolving-error-external-table-is-not-in-expected-format
The recommendation is to save as Excel 2003
Just adding my solution to this issue. I was uploading a .xlsx file to the webserver, then reading from it and bulk inserting to SQL Server. Was getting this same error message, tried all the suggested answers but none worked. Eventually I saved the file as excel 97-2003 (.xls) which worked... only issue I have now is that the original file had 110,000+ rows.
If you still have this problem, then check your permissions, I tried many of these suggestions and my concrete problem was that the file that I wanted to process was under source control and the thread had no permissions, I had to change the entire folder permissions and it started to work (I was processing many files in there)... It also matches many suggestions like change the name of the file or check that the file is not loicked by another process.
I hope it helps you.
Instead of OleDb, you could use the Excel Interop and open the worksheet as read-only.
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.open(v=office.15).aspx
This can occur when the workbook is password-protected. There are some workarounds to remove this protection but most of the examples you'll find online are outdated. Either way, the simple solution is to unprotect the workbook manually, otherwise use something like OpenXML to remove the protection programmatically.
I recently saw this error in a context that didn't match any of the previously listed answers. It turned out to be a conflict with AutoVer. Workaround: temporarily disable AutoVer.
That excel file address may have an incorrect extension. You can change the extension from xls to xlsx or vice versa and try again.
I recently had this "System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format." error occur. I was relying on Microsoft Access 2010 Runtime. Prior to the update that was automatically installed on my server on December 12th 2018 my C# code ran fine using Microsoft.ACE.OLEDB.12.0 provider. After the update from December 12th 2018 was installed I started to get the “External table is not in the expected format" in my log file.
I ditched the Microsoft Access 2010 Runtime and installed the Microsoft Access 2013 Runtime and my C# code started to work again with no "System.Data.OleDb.OleDbException (0x80004005): External table is not in the expected format." errors.
2013 version that fixed this error for me
https://www.microsoft.com/en-us/download/confirmation.aspx?id=39358
2010 version that worked for me prior to the update that was automatically installed on my server on December 12th.
https://www.microsoft.com/en-us/download/confirmation.aspx?id=10910
https://www.microsoft.com/en-us/download/confirmation.aspx?id=10910
I also had this error occur last month in an automated process. The C# code ran fine when I ran it debugging. I found that the service account running the code also needed permissions to the C:\Windows\Temp folder.
Working with some older code and came across this same generic exception. Very hard to track down the issue, so I thought I'd add here in case it helps someone else.
In my case, there was code elsewhere in the project that was opening a StreamReader on the Excel file before the OleDbConnection tried to Open the file (this was done in a base class).
So basically I just needed to call Close() on the StreamReader object first, then I could open the OleDb Connection successfully. It had nothing to do with the Excel file itself, or with the OleDbConnection string (which is naturally where I was looking at first).
I've had this occur on a IIS website that I host, rarely but periodically this error will popup for files that I've previously parsed just fine. Simply restarting the applicable app pool seems to resolve the issue. Not quite sure why though...
This happened to us just recently. A customer of ours was getting this error when trying to upload their excel file on our website. I could open the xlsx file fine on ms excel and don't see any irregularities with the file. I've tried all mentioned solutions in here and none worked. And i found this link Treating data as text using Microsoft.ACE.OLEDB.12.0. What worked for our case is adding IMEX=1 attribute to the connection string. So if you are using Microsoft ACE OLEDB 12.0 this might help fix your issue. Hope this helps.
<add name="ExcelTextConnection" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1};IMEX=1'" />

Categories