Строка подключения oledb к excel

CData ADO.NET Provider for Excel

Microsoft ACE OLEDB 12.0

Xlsx files

Connect to Excel 2007 (and later) files with the Xlsx file extension. That is the Office Open XML format with macros disabled.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";

Treating data as text

Use this one when you want to treat all data in the file as text, overriding Excels column type «General» to guess what type of data is in the column.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";

Xlsb files

Connect to Excel 2007 (and later) files with the Xlsb file extension. That is the Office Open XML format saved in a binary format. I e the structure is similar but it’s not saved in a text readable format as the Xlsx files and can improve performance if the file contains a lot of data.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyBinaryExcel2007file.xlsb;Extended Properties="Excel 12.0;HDR=YES";

Xlsm files

Connect to Excel 2007 (and later) files with the Xlsm file extension. That is the Office Open XML format with macros enabled.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyExcel2007file.xlsm;Extended Properties="Excel 12.0 Macro;HDR=YES";

Excel 97-2003 Xls files with ACE OLEDB 12.0

You can use this connection string to use the Office 2007 OLEDB driver (ACE 12.0) to connect to older 97-2003 Excel workbooks.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyOldExcelFile.xls;Extended Properties="Excel 8.0;HDR=YES";

Microsoft Jet OLE DB 4.0

Standard (Excel)

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";

Standard alternative

Try this one if the one above is not working. Some reports that Excel 2003 need the exta OLEDB; section in the beginning of the string.

OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";

.NET Framework Data Provider for OLE DB

Microsoft Excel 2007 ODBC Driver

Standard

Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=C:MyExcel.xlsx;

Standard (for versions 97 — 2003)

Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=C:MyExcel.xls;

Microsoft Excel ODBC Driver

Standard

Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:MyExcel.xls;DefaultDir=c:mypath;

Specify ReadOnly

[Microsoft][ODBC Excel Driver] Operation must use an updateable query. Use this connection string to avoid the error.

Driver={Microsoft Excel Driver (*.xls)};Dbq=C:MyExcel.xls;ReadOnly=0;

.NET Framework Data Provider for ODBC

.NET xlReader for Microsoft Excel

This reference section describes additional connection string information when using EDT to load data directly from an Excel spreadsheet file.

The Excel Database Tasks (EDT) software can load data from ANY source either as an Excel report,

or Validate and send the data to any destination Table or Stored Procedure. 

Supporting MS SQL Server, Oracle, MySQL, Access, DB2 databases.

Download EDT Free Trial

A connection string can be pasted into the EDT Data Source connection string text box as highlighted below.

After modifying the connection string,  click the Test button to verify the connection:

Microsoft ACE OLEDB 12.0

Microsoft ACE driver will allow you to query Office files (Including Access database AND Excel files)

ACE driver is available from Microsoft here:


Xlsx files 

Connect to Excel 2007 (and later) files with the Xlsx file extension. That is the Office Open XML format with macros disabled.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyExcel2007file.xlsx;

Extended Properties=»Excel 12.0 Xml;HDR=YES»;

«HDR=Yes;» indicates that the first row contains column names, not data. «HDR=No;» indicates the opposite.



Treating data as text

Use this one when you want to treat all data in the file as text, overriding Excels column type «General» to guess what type of data is in the column.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyExcel2007file.xlsx;

Extended Properties=»Excel 12.0 Xml;HDR=YES;IMEX=1″;

If you want to read the column headers into the result set (using HDR=NO even though there is a header) and the column data is numeric, use IMEX=1 to avoid crash.To always use IMEX=1 is a safer way to retrieve data for mixed data columns. Consider the scenario that one Excel file might work fine cause that file’s data causes the driver to guess one data type while another file, containing other data, causes the driver to guess another data type. This can cause your app to crash.


Xlsb files

Connect to Excel 2007 (and later) files with the Xlsb file extension. That is the Office Open XML format saved in a binary format. I e the structure is similar but it’s not saved in a text readable format as the Xlsx files and can improve performance if the file contains a lot of data.

Provider=Microsoft.ACE.OLEDB.12.0;

Data Source=c:myFoldermyBinaryExcel2007file.xlsb;

Extended Properties=»Excel 12.0;HDR=YES»;

You can also use this connection string to connect to older 97-2003 Excel workbooks.»HDR=Yes;» indicates that the first row contains columnnames, not data. «HDR=No;» indicates the opposite.

Xlsm files
Connect to Excel 2007 (and later) files with the Xlsm file extension. That is the Office Open XML format with macros enabled.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyExcel2007file.xlsm;

Extended Properties=»Excel 12.0 Macro;HDR=YES»;

«HDR=Yes;» indicates that the first row contains column names, not data. «HDR=No;» indicates the opposite.


Excel 97-2003 Xls files with ACE OLEDB 12.0

You can use this connection string to use the Office 2007 OLEDB driver (ACE 12.0) to connect to older 97-2003 Excel workbooks.

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:myFoldermyOldExcelFile.xls;

Extended Properties=»Excel 8.0;HDR=YES»;

«HDR=Yes;» indicates that the first row contains column names, not data. «HDR=No;» indicates the opposite. 

Microsoft Jet OLE DB 4.0


Standard (Excel)

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:MyExcel.xls;

Extended Properties=»Excel 8.0;HDR=Yes;IMEX=1″;

How to Use JET in 64 bit environments 


Standard alternative

Try this one if the one above is not working. Some reports that Excel 2003 need the exta OLEDB; section in the beginning of the string.

OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:MyExcel.xls;Extended Properties=»Excel 8.0;HDR=Yes;IMEX=1″;

«HDR=Yes;» indicates that the first row contains column names, not data. «HDR=No;» indicates the opposite.»IMEX=1;» tells the driver to always read «intermixed» (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative.SQL syntax «SELECT [Column Name One], [Column Name Two] FROM [Sheet One$]». I.e. excel worksheet name followed by a «$» and wrapped in «[» «]» brackets.Check out the [HKEY_LOCAL_MACHINESOFTWAREMicrosoftJet4.0EnginesExcel] located registry REG_DWORD «TypeGuessRows». That’s the key to not letting Excel use only the first 8 rows to guess the columns data type. Set this value to 0 to scan all rows. This might hurt performance. Please also note that adding the IMEX=1 option might cause the IMEX feature to set in after just 8 rows. Use IMEX=0 instead to be sure to force the registry TypeGuessRows=0 (scan all rows) to work.If the Excel workbook is protected by a password, you cannot open it for data access, even by supplying the correct password with your connection string. If you try, you receive the following error message: «Could not decrypt file.»


.NET Framework Data Provider for OLE DB


Use an OLE DB provider from .NET

Provider=any oledb provider’s name;OledbKey1=someValue;OledbKey2=someValue;

See the respective OLEDB provider’s connection strings options. The .net OleDbConnection will just pass on the connection string to the specified OLEDB provider. 


Microsoft Excel 2007 ODBC Driver

Standard

Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};

DBQ=C:MyExcel.xlsx;


Standard (for versions 97 — 2003)

Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};

DBQ=C:MyExcel.xls;

Standard

Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:MyExcel.xls;

DefaultDir=c:mypath;

SQL syntax «SELECT [Column Name One], [Column Name Two] FROM [Sheet One$]». I.e. excel worksheet name followed by a «$» and wrapped in «[» «]» brackets.


Specify ReadOnly

[Microsoft][ODBC Excel Driver] Operation must use an updateable query. Use this connection string to avoid the error.

Driver={Microsoft Excel Driver (*.xls)};Dbq=C:MyExcel.xls;ReadOnly=0;

ReadOnly = 0 specifies the connection to be updateable. 


.NET Framework Data Provider for ODBC


Use an ODBC driver from .NET

Driver={any odbc driver’s name};OdbcKey1=someValue;OdbcKey2=someValue;

See the respective ODBC driver’s connection strings options. The .net Odbc Connection will just pass on the connection string to the specified ODBC driver.


.NET xlReader for Microsoft Excel


Excel file with header row

Data Source =c:myExcelFile.xlsx;HDR=yes;Format=xlsx;


Excel file without header row

Data Source =c:myExcelFile.xlsx;HDR=no;Format=xlsx;


Excel file with header row (for versions 97 — 2003)

Data Source =c:myExcelFile.xls;HDR=yes;Format=xls;


Excel file without header row (for versions 97 — 2003)

Data Source =c:myExcelFile.xls;HDR=no;Format=xls;

RSSBus ADO.NET Provider for Excel

Standard
Excel File=C:myExcelFile.xlsx;


No headers in Excel sheet

Excel File=C:myExcelFile.xlsx;Header=False;
Pseudo column names (A,B,C) are used instead. 


Caching data

Excel File=C:myExcelFile.xlsx;Cache Location=C:cache.db;Auto Cache=true;
Offline=false;
To retrieve data from the cache, add «#Cache» to the table name. For example, to query cached data from the «Sheet» table, execute «SELECT * FROM [Sheet#Cache]». 


Caching data and metadata

Excel File=C:myExcelFile.xlsx;Cache Location=C:cache.db;Auto Cache=true;
Offline=false;Cache Metadata=true;
The table metadata will also be cached instead of retrieving it from the data source. This improves connection performance. 


Cached data only / Offline mode

Excel File=C:myExcelFile.xlsx;Offline=true;Query Passthrough=true;
Cache Location=C:cache.db;
SELECT statements will always retrieve data from the cache. DELETE/UPDATE/INSERT statements is not allowed and will throw an exception. Excel 2000Excel 2002Excel 2003Excel 2007Excel 2010Excel 2013Excel 97


Using an External Cache Provider

RSSBus drivers have the ability to cache data in a separate database such as SQL Server or MySQL instead of in a local file using the following syntax:
Cache Provider=Provider.Namespace;
Cache Connection=’Connection String to Cache Database’;
Above is just an example to show how it works. It can be used both with «Auto Cache» and with «Cached Data Only / Offline Mode». 


Empty cells always NULL

Excel File=C:myExcelFile.xlsx;Empty Text Mode=EmptyAsNull;


Empty cells always empty string

Excel File=C:myExcelFile.xlsx;Empty Text Mode=NullAsEmpty;


Suppress formula calculation errors

Excel File=C:myExcelFile.xlsx;Ignore Calc Error=true;


Read «tilted sheets», where rows are headers and columns are rows

Excel File=C:myExcelFile.xlsx;Orientation=Horizontal;


Do not use formulas, only values

Do not treat values starting with equals (=) as formulas during inserts and updates.
Excel File=C:myExcelFile.xlsx;Allow Formula=false;

Провайдеры данных

Для работы с Excel 2003 (.Xls) можно использовать провайдер Microsoft Jet OLE DB 4.0.

SELECT * FROM OPENROWSET(
	'Microsoft.Jet.OLEDB.4.0', 
	'Excel 12.0;Database=d:tmpTimeSheets.xlsx;HDR=YES;IMEX=1', 
	'SELECT * FROM [Sheet1$]');

Для работы с Excel 2007 (.Xlsx) — Microsoft ACE OLEDB 12.0.

SELECT * FROM OPENROWSET (
    'Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;Database=d:tmpTimeSheets.xlsx;HDR=YES;IMEX=1',
    'SELECT * FROM [Sheet1$]');

В Windows 10 открыть настройки источников данных ODBC можно написав «Источники данных ODBC» или через Панель управления Администрирование.

Extended Properties

  • HDR=YES|NO. HDR=YES означает, что первую строку листа, следует рассматривать как заголовки колонок. Т.о. значение из первой строки можно использовать как имена полей в sql запросах (любых: select, insert, update, delete).
  • IMEX=1|3. 1 — открыть соединение для чтения. 3 — для записи.

Создание Linked Server в Sql Server для доступа к Excel

EXEC sp_addLinkedServer
    @server= N'XLSX_2010',
    @srvproduct = N'Excel',
    @provider = N'Microsoft.ACE.OLEDB.12.0',
    @datasrc = N'd:tmpTimeSheets.xlsx',
    @provstr = N'Excel 12.0; HDR=Yes';
GO

После создания связанного сервера можно будет просмотреть имена доступных листов.

Затем, чтобы обратиться к сервису:

SELECT * FROM OPENQUERY (XLSX_2010, 'Select * from [Sheet1$]')
или
SELECT * FROM [XLSX_2010]...[Лист1$]

Обращение к лиcтам, диапазонам, полям

Для обращения к листу из SQL запроса нужно использовать имя листа, например: [Sheet1$] или [Лист1$]. Обращение к диапазону: [Sheet1$A16:F16].

Вставка данных в произвольное место

Примеры указания диапазона при вставке строк (insert)

  • [table1$B4:E20]
  • [table1$S4:U]
  • [table1$F:G]

При вставке должны выполняться следующие условия:

  • Первая строчка указанного диапазона дожна входить в диапазон ячеек с данными. Чтобы создать на листе диапазон с данными достаточно в углах некоторого прямоугольного диапазона (в левом верхнем и правом нижнем) вписать значение (C4:I7 на скриншоте). Т.е. сама первая строчка указанного в insert диапазона данные содержать не обязана, достаточно, чтобы она просто входила в такой диапазон. Иначе возникнет ошибка "This table contains cells that are outside the range of cells defined in this spreadsheet"
  • Хвост диапазона должен содержать пустые строки (хотя бы одну).

Пример: Дан лист, где заполнены только 2 ячейки: C4, I7. После выполнения команды INSERT INTO [table1$E6:G] VALUES(2, 'FF','2014-01-03') результат будет как на скриншоте. Поясним: строка E6:G6 является первой строкой диапазона для вставки. Она входит в заполненный диапазон C4:I7. Поэтому данные были вставлены на следующей пустой строке — 8. Из этого примера становится ясно, что через OleDb нельзя работать с несколькими независимыми диапазонами на одном листе, используя вставку (update будет работать).

Insert

Ошибки

  • System.Data.OleDb.OleDbException (0x80004005): Operation must use an updateable query. Соединение открыто для чтение, при этом происходит попытка внести изменения (выполнить insert, update или delete). Решение: открыть соединение для записи, установив свойство провайдера в строке соединения IMEX=3 (см. выше).
  • System.Data.OleDb.OleDbException (0x80004005): "This table contains cells that are outside the range of cells defined in this spreadsheet". Такая ошибка возникает при подпытке обновить (update) или вставить (insert) значения в диапазоне, в котором отсутствуют данные на листе.
    1. Если нужно произвести запись в определенные ячейки инструкцией update, то

Ссылки

  • https://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
  • https://stackoverflow.com/questions/36987636/cannot-create-an-instance-of-ole-db-provider-microsoft-jet-oledb-4-0-for-linked
  • https://stackoverflow.com/questions/26267224/the-ole-db-provider-microsoft-ace-oledb-12-0-for-linked-server-null
  • http://www.ashishblog.com/importexport-excel-xlsx-or-xls-file-into-sql-server/
  • https://yoursandmyideas.com/2011/02/05/how-to-read-or-write-excel-file-using-ace-oledb-data-provider/
  • https://stackoverflow.com/questions/46373895/how-to-open-a-huge-excel-file-efficiently Несколько способов открыть большой Excel файл, в т.ч. с помощью OleDb.

The problem i’m having is that the data adapter is looking at only the first row in each column to determine the data type. In my case the first column «SKU» is numbers for the first 500 rows then I happen to have SKU’s which are mixed numbers and letters. So what ends up happening is rows in the SKU column are left blank, but I still get the other information for each column row.

I believe it is the connection string that controls that and with my current settings it should work, however it is not.

Connection String:

conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersNickDesktopPricing2.xlsx" + @";Extended Properties=""Excel 12.0 Xml;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
ImportMixedTypes=Text;TypeGuessRows=0

Should be the important keywords, look at 0 rows and just use text as the value types for everything.

The «bandaid» I have put on this is to make the first row in the spreadsheet a mixture of letters and numbers and specifically leave that row out in my query.

asked Dec 29, 2010 at 3:12

The Muffin Man's user avatar

The Muffin ManThe Muffin Man

19.4k30 gold badges119 silver badges190 bronze badges

3

Unfortunately, you can’t set ImportMixedTypes or TypeGuessRows from the connection string since those settings are defined in the registry. For the ACE OleDb driver, they’re stored at

HKEY_LOCAL_MACHINESOFTWAREMicrosoftOffice14.0Access Connectivity EngineEnginesExcel

in the registry. So, you can simplify your connection string to:

conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersNickDesktopPricing2.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes;IMEX=1;""";

Once you set TypeGuessRows to 0 and ImportMixedTypes to Text in the registry, you should get the behavior you are expecting. You might, however, consider using a suitably large number like 1000 instead of zero if you find import performance to be less than ideal.

answered Jan 11, 2011 at 23:02

arcain's user avatar

arcainarcain

14.8k6 gold badges55 silver badges75 bronze badges

8

В этой статье опишу как прочитать Excel с помощью OleDB.

Иногда бывает нужно вытянуть таблицу из Excel документа, записать в DataTable для последующей обработки.

Не всегда это удобно делать с помощью циклов, поэтому будем считывать таблицы, содержащиеся в документе и запрашивать из них данные с помощью SQL запросов.

oledb C#

Определение строки подключения

Для разных версий Excel будут свои строки подключения.

Строка подключения для Excel 2007 и более новых версий

//Можно использовать, если количество строк менее 65536
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'

//Если строк больше 65536
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties="Excel 12.0 Xml;HDR=YES";

Для работы с данными версиями необходимо установить Microsoft Access Database Engine 2010 Redistributable.

Так же C# может выбрасывать исключения по поводу недостающих драйверов. В этом случае необходимо скачать соответствующие драйверы с сайта Microsoft.

Строка подключения для более ранних версий

Строка подключения для Excel версии 2003 может иметь такой вид:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'

Если C# выбросит исключение, скачайте недостающий драйвер, Visual Studio подскажет, какой.

Как сделать SQL запрос из таблицы Excel

Для выполнения SQL запроса нужно найти таблицу в документе и выполнить к ней запрос:

//Объявляем OleDB соединение
using(OleDbConnection conn = new OleDbConnection(conStr))
{
  //Открываем подключение
  conn.Open();
  //Запрашиваем таблицы
  DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  DataRow schemaRow = schemaTable.Rows[0];
  //Получаеи имя таблицы
  string sheet = schemaRow["TABLE_NAME"].ToString();
  //Объявляем команду
  OleDbCommand com = conn.CreateCommand();
  //Создаем SQL запрос
  com.CommandText = "SELECT * FROM [" + sheet + "]";
  //Выполняем SQL запрос
  OleDbDataReader reader = com.ExecuteReader();
  //Записываем результат в DataTable
  DataTable table = new DataTable();
  table.Load(reader);
  //Выводим DataTable в таблицу на форму (если нужно)
  gridControl1.DataSource = table;
}

На этом шаге мы имеем считанные данные из Excel документа в DataTable.

После обработки данных можно сохранить данные в другой документ или оформить сводную таблицу.

Как работать с Excel с помощью C# обсуждалось ранее.

Так же можете посмотреть, как работать со сводными таблицами в Excel с помощью C# и редактора VBA, встроенного в Excel.


Просмотрено:
7 446

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Строка повторяется на каждой странице excel
  • Строка перед строкой excel
  • Строка панелей в 2 строки в excel
  • Строка основного меню excel это
  • Строка набора в word

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии