Внешняя таблица не имеет предполагаемый формат excel sql

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);
}

pnuts's user avatar

pnuts

58k11 gold badges85 silver badges137 bronze badges

asked Jul 16, 2009 at 18:23

Sisiutl's user avatar

1

«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:srcRedirectApplicationRedirectApplication301s.xlsx";
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

answered Sep 1, 2009 at 16:38

FAtBalloon's user avatar

FAtBalloonFAtBalloon

4,4701 gold badge24 silver badges33 bronze badges

12

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;"""

Arseni Mourzenko's user avatar

answered Feb 11, 2010 at 6:38

Trex's user avatar

TrexTrex

2893 silver badges2 bronze badges

2

(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.

Eunoseer's user avatar

Eunoseer

753 silver badges10 bronze badges

answered Feb 25, 2011 at 14:10

cederlof's user avatar

cederlofcederlof

7,1044 gold badges44 silver badges62 bronze badges

3

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.

answered Jan 22, 2016 at 12:25

Fengtao Ding's user avatar

4

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)

enter image description here

4.) Select Excel 97-2003 Workbook

enter image description here

5.) Click on Save button

enter image description here

answered Mar 13, 2019 at 6:49

Kamran's user avatar

KamranKamran

6596 silver badges8 bronze badges

1

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 FilesCommon FilesMicrosoft SharedOFFICE14ACEOLEDB.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: HKCRCLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}InprocServer32

Value Name: (Default)

Value Data: C:Program FilesCommon FilesMicrosoft
SharedOFFICE14ACEOLEDB.DLL

(OS: 64bit Office: 32bit)

Key:
HKCRWow6432NodeCLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}InprocServer32

Value Name: (Default)

Value Data: C:Program Files (x86)Common FilesMicrosoft
SharedOFFICE14ACEOLEDB.DLL

Community's user avatar

answered Jun 5, 2013 at 12:46

jordanhill123's user avatar

jordanhill123jordanhill123

4,1222 gold badges30 silver badges40 bronze badges

1

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.

answered May 11, 2012 at 19:33

John M. Black's user avatar

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.

answered Jul 4, 2014 at 18:06

John M's user avatar

John MJohn M

14.2k29 gold badges90 silver badges139 bronze badges

If the file is read-only, just remove it and it should work again.

answered Feb 4, 2019 at 22:25

Tehscript's user avatar

TehscriptTehscript

2,5762 gold badges13 silver badges22 bronze badges

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.

enter image description here

answered Nov 18, 2020 at 14:14

MMJ's user avatar

MMJMMJ

5254 silver badges6 bronze badges

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"";"

answered Jun 24, 2016 at 13:07

majjam's user avatar

majjammajjam

1,2762 gold badges15 silver badges32 bronze badges

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();

Community's user avatar

answered Oct 3, 2016 at 11:14

Akshay Upadhyay's user avatar

3

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.

answered Jun 27, 2018 at 8:02

kerwei's user avatar

kerweikerwei

1,8021 gold badge13 silver badges22 bronze badges

1

the file might be locked by another process, you need to copy it then load it as it says in this post

answered Feb 16, 2014 at 23:58

user3140982's user avatar

user3140982user3140982

1351 gold badge3 silver badges8 bronze badges

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.

answered Jun 17, 2015 at 9:47

Kieran Quinn's user avatar

Kieran QuinnKieran Quinn

1,0651 gold badge22 silver badges49 bronze badges

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.

answered Feb 16, 2016 at 6:32

Juan's user avatar

JuanJuan

2,13617 silver badges26 bronze badges

Paulo Henrique Queiroz's user avatar

answered Jul 16, 2009 at 18:33

Nelson's user avatar

NelsonNelson

4644 silver badges10 bronze badges

3

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.

answered Feb 2, 2017 at 15:25

KthProg's user avatar

KthProgKthProg

2,0201 gold badge23 silver badges32 bronze badges

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.

answered Apr 26, 2017 at 17:46

unbob's user avatar

unbobunbob

3313 silver badges7 bronze badges

That excel file address may have an incorrect extension. You can change the extension from xls to xlsx or vice versa and try again.

answered Jun 27, 2018 at 8:25

MiMFa's user avatar

MiMFaMiMFa

9049 silver badges14 bronze badges

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:WindowsTemp folder.

answered Dec 20, 2018 at 20:12

vvvv4d's user avatar

vvvv4dvvvv4d

3,8511 gold badge13 silver badges18 bronze badges

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).

answered Aug 2, 2019 at 19:04

tbone's user avatar

tbonetbone

15k3 gold badges33 silver badges40 bronze badges

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…

answered Feb 4, 2022 at 19:49

David Rogers's user avatar

David RogersDavid Rogers

2,5214 gold badges41 silver badges82 bronze badges

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'" />

answered Apr 14, 2022 at 17:47

sd4ksb's user avatar

sd4ksbsd4ksb

2311 gold badge4 silver badges15 bronze badges

  • Remove From My Forums
  • Question

  • I am trying to import an Excel spreadsheet using the Import export wizard that is provided with SQL 2014.  

    Everything seems to set up OK but then when I go to do the transfer «error message» comes up saying:

    External Table is not in the expected format.(Microsoft Jet Database Engine).   

    This is a spreadsheet and there is no database, that is why I want to import it into a database!!  So the reference to JET is a tad disappointing.

    So why the error and how do I fix the problem?

    As there are over 100 variables in the spread sheet rows, it would be great to have this automatically create the database and populate the fields.

    I am using SQL 2014  Express and Office Excel 2013.

    Thank you in  advance for taking the time to read this, and hopefully sheading some light on the issue.

    • Moved by

      Friday, October 24, 2014 6:14 AM
      The import and export wizard is provided by SSIS. Move the post to SSIS forum

Answers

  • Hi AWlcurrent,

    When import a .xlsx file to SQL Server using SQL Server Import and Export Wizard, you see a “External Table is not in the expected format.(Microsoft Jet Database Engine).” error message. This error message seems that the Microsoft JET Database Engine is
    unable to handle something that is contained in the file.

    So please make sure there is no unsupported content in the Excel file. Alternatively, we can use ‘Microsoft Excel’ as the Data Source, then Select ‘Microsoft Excel 2007’ as the Excel version to import the excel file.

    If there are any other questions, please feel free to ask.

    Thanks,
    Katherine Xiong

    If you have any feedback on our support, please click
    here.


    Katherine Xiong
    TechNet Community Support

    • Marked as answer by
      Katherine Xiong
      Thursday, October 30, 2014 3:55 AM

  • It turned out that there are two versions of the import wizard.   I by mistake used the 32 bit version when my database is 64.

    That turned out to be the problem.

    • Marked as answer by
      Katherine Xiong
      Friday, November 14, 2014 1:17 AM

Добрый день!!!
Excell 2010.  в PQ был создан запрос из папки в которой ежедневно появляются новые файлы xls.
При обновлении итогового запроса Выдается сообщение:

Не удается подключить
Произошла ошибка при попытке подключения.
Подробности: «Внешняя таблица не имеет предполагаемый формат»

Не соображу в чем дело, помогите пожалуйста.  Ошибка выдается при попытке первого  обновления после изменения состава папки-источника.
PQ проглатывает  ошибку и обновляет запрос только  после того как  войдешь в папку и откроешь новый файл/ на котором споткнулся PQ.

Если нужны подробности — подскажите пожалуйста откуда именно их взять, очень на ВЫ с PQ.
Заранее большое спасибо!!!!!

Community,

I am having a problem importing files from a sharepoint folder (6 files that need to be brought together). I see these as .xls files in Sharepoint and therefore use:

     let
         Source = Folder.Files(…. /sharepoint location»…….),

// no problem
    #»Removed Other Columns» = Table.SelectColumns(Source,{«Content»}),
    #»Added Custom» = Table.AddColumn(#»Removed Other Columns», «GetExcelData», each Excel.Workbook([Content])),

//no problem — I am able to see all the data in PowerQuery

Everything looks fine — ready to go.

However, when I hit «Close and Apply» — the system returns an error:

     [DataFormat.Error] External table is not in the expected format.

The original files generated from a SQL query — and then the results of the query are pasted into an Excel file…. The orginal response that is being pasted is a tab delimited file — which may be causing the problem at some level.   

Is there a different approach I should be using to open these files? Instead of Excel.Workbook([Content}) is there a something else that will be more appropriate for a tab delimited file?

Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public async Task UploadEmployeesAsync(string pathToFile)
{
    string excelConnectionString = GetExcelConnectionString(pathToFile); // Метод из BaseDA
 
    DataTable excelDataTable = new DataTable();
 
    excelDataTable.Columns.AddRange(new DataColumn[12]
    {
        new DataColumn("PersonalNumber",typeof(string)),
        new DataColumn("LastName",typeof(string)),
        new DataColumn("FirstName",typeof(string)),
        new DataColumn("SecondName",typeof(string)),
        new DataColumn("DateOfBirth",typeof(DateTime)),
        new DataColumn("PhoneNumber",typeof(string)),
        new DataColumn("EMail",typeof(string)),
        new DataColumn("EmploymentDate",typeof(DateTime)),
        new DataColumn("DismissalDate",typeof(DateTime)),
        new DataColumn("Foreigner",typeof(int)),
        new DataColumn("Country",typeof(string)),
        new DataColumn("Position",typeof(string))
    });
 
    string excelQuery =
        "SELECT PersonalNumber, LastName, FirstName, SecondName, DateOfBirth, PhoneNumber, EMail, " +
        "EmploymentDate, DismissalDate, Foreigner, Country, [Position] " +
        "FROM [tblHRDEmployee$]";
 
    try
    {
        using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter(excelQuery, excelConnectionString))
        {
            oleDbDataAdapter.Fill(excelDataTable);
        }
 
        using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
        {
            await sqlConnection.OpenAsync();
 
            using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction())
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection,
                       SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.CheckConstraints,
                       sqlTransaction))
                {
                    sqlBulkCopy.DestinationTableName = "dbo.tblHRDEmployee";
 
                    sqlBulkCopy.ColumnMappings.Add("PersonalNumber", "PersonalNumber");
                    sqlBulkCopy.ColumnMappings.Add("LastName", "LastName");
                    sqlBulkCopy.ColumnMappings.Add("FirstName", "FirstName");
                    sqlBulkCopy.ColumnMappings.Add("SecondName", "SecondName");
                    sqlBulkCopy.ColumnMappings.Add("DateOfBirth", "DateOfBirth");
                    sqlBulkCopy.ColumnMappings.Add("PhoneNumber", "PhoneNumber");
                    sqlBulkCopy.ColumnMappings.Add("EMail", "EMail");
                    sqlBulkCopy.ColumnMappings.Add("EmploymentDate", "EmploymentDate");
                    sqlBulkCopy.ColumnMappings.Add("DismissalDate", "DismissalDate");
                    sqlBulkCopy.ColumnMappings.Add("Foreigner", "Foreigner");
                    sqlBulkCopy.ColumnMappings.Add("Country", "Country");
                    sqlBulkCopy.ColumnMappings.Add("Position", "Position");
 
                    try
                    {
                        await sqlBulkCopy.WriteToServerAsync(excelDataTable);
                        sqlTransaction.Commit();
                    }
                    catch (Exception tranEx)
                    {
                        sqlTransaction.Rollback();
                        throw new ApplicationException("Ошибка транзакции вставки данных", tranEx);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        throw new ApplicationException("Ошибка загрузки данных", ex);
    }
}

Понравилась статья? Поделить с друзьями:
  • Внедренный объект в word это
  • Внешняя ссылка на ячейка excel
  • Внедренный в файл microsoft word
  • Внешняя ссылка в excel это пример
  • Внедренная диаграмма excel это