Oracle sql and excel

Задача. У вас есть файл Excel – и вы хотите, чтобы эти данные были помещены в таблицу. Я покажу вам, как это делается, и мы задокументируем каждый шаг с большим количеством иллюстраций.

Прочитав этот пост, вы будете готовы с уверенностью импортировать данные в существующую таблицу из Excel. Хотите создать новую таблицу из Excel? Мы тоже можем это сделать.

В нашем примере я буду использовать таблицу HR.EMPLOYEES для создания XLS-файла для нашего импорта. Мы будем использовать этот файл Excel для заполнения пустой копии таблицы EMPLOYEES в другой схеме.

Шаг 0: Пустая таблица Oracle и ваш файл Excel

У вас есть таблица Oracle и один или несколько файлов Excel.

Шаг 1: Выбираем «Импорт данных» по правому щелчку мыши

Шаг 2: Выберите свой входной файл (XLSX) и проверьте данные

Если вы уже запускали этот мастер раньше, вы можете выбрать файлы из предыдущих сеансов.

Когда вы выберете файл, мы захватим первые 100 строк для просмотра ниже. Этот «Предел строк предварительного просмотра» определяет, сколько строк вы можете использовать для проверки ИМПОРТА по мере прохождения мастера. Вы можете увеличить его, но это потребует больше ресурсов, так что не сходите с ума.

Кроме того, есть ли в вашем файле Excel заголовки столбцов? Хотим ли мы рассматривать их как строку к таблице? Скорее всего, нет. Если вы снимите флажок «Заголовок», имена столбцов станут новой строкой в вашей таблице – и, вероятно, не будут вставлены.

Иногда ваш файл Excel имеет несколько заголовков, или вам может потребоваться импортировать только определенное подмножество электронной таблицы. Используйте опцию «Пропустить строки», чтобы получить правильные данные.

Шаг 3: Создайте сценарий или импортируйте автоматически

По мере прохождения шагов в мастере мы будем держать панель предварительного просмотра содержимого файла под рукой, так что вам не придется нажимать  alt+tab туда и обратно от Excel до SQL Developer.

Для этого упражнения будет использоваться метод «Вставки» (Insert). Каждая строка, обработанная в файле Excel, приведет к выполнению инструкции INSERT в таблице, в которую мы импортируем.

Если вы выберете «Вставить скрипт», мастер завершит работу скриптом ВСТАВКИ на вашем листе SQL. Это хорошая альтернатива, если вы хотите настроить SQL, или если вам нужно отладить/посмотреть, почему метод «Insert» не работает.

Шаг 4: Выберите столбцы Excel для импорта

Мастер по умолчанию использует все используемые столбцы Excel в том порядке, в котором они находятся в файле.

У вас может быть файл Excel со 100 столбцами, но ваша таблица имеет только 30. Здесь вы даете команду SQL Developer, какие столбцы должны использоваться для импорта. Вы также можете изменить порядок столбцов, что может сделать следующий шаг немного проще.

Шаг 5: Сопоставьте столбцы Excel со столбцами таблицы

Левая панель представляет столбцы в файле XLS. Информация справа показывает, куда идут эти данные и как они будут обрабатываться в Oracle.

Если вы не обращаете внимания и просто позволяете Мастеру импорта делать всё по умолчанию, то сейчас самое время проснуться. Есть большая вероятность, что порядок столбцов файла Excel не будет соответствовать определению вашей таблицы. На этом шаге вы указываете SQL Developer-у, какие столбцы в электронной таблице совпадают с какими столбцами в таблице Oracle.

А помните, как мы установили это окно предварительного просмотра на 100 строк? Мы внимательно изучаем данные, ищем проблемы, пытаясь вписать их в столбец вашей таблицы. Если мы обнаружим проблему, мы пометим столбцы этими «предупреждающими» символами.

Я загрязнил свой файл Excel некоторыми намеренно ошибочными значениями, которые, как я знаю, не будут «подходить». Когда эти строки будут обнаружены в мастере, база данных их отклонит, но остальные строки будут введены.

Давайте на секунду поговорим о форматах даты и времени.

О TIMESTAMP тоже. В файле Excel у вас, вероятно, будут некоторые поля даты и времени, которые вы хотите переместить в столбцы формата  DATE или TIMESTAMP. SQL Developer обрабатывает эти значения как строки – и ВАМ нужно сообщить SQL Developer формат DATE или TIMESTAMP, чтобы иметь возможность их преобразовать.

Давайте посмотрим на HIREDATE.

Это значение «ха – ха» никогда не войдет в качестве значения HIRE_DATE – если только вы не храните ДАТЫ в VARCHAR2, — и если вы делаете это, то делаете это НЕПРАВИЛЬНО. Всегда храните ДАТЫ в формате DATE!

Видите выпадающий селектор «Формат» (Format)? SQL Developer по умолчанию установил строку формата ДАТЫ в ‘DD-MON-RR’ – мы пытаемся угадать это на основе строк, которые мы рассматриваем в этом окне предварительного просмотра 100.

Если мы ошиблись в догадках или не смогли разобраться, вам нужно будет ввести это самостоятельно. Документы Oracle могут помочь вам определить правильную модель формата ДАТЫ. Если вы видите небольшое предупреждающее изображение рядом со значениями даты на панели данных, возможно, у вас неправильный формат.

Шаг 6: Проверьте свои настройки и ВПЕРЕД!

Кнопка «Готово» запустит магию.

Нажмите на кнопку «Готово» (Finish).

Если Мастер столкнется с какими-либо проблемами при выполнении вставок, вы увидите следующее:

Помните те забавные данные, которые я поместил в файл Excel? Теперь это создает проблемы.

Я собираюсь сказать «Да», чтобы игнорировать все ошибки. Но если вам нужна КАЖДАЯ отдельная строка – вам нужно сказать «Отмена», чтобы начать все сначала. Затем вы можете либо исправить свои данные в файле Excel, либо внести изменения в свою таблицу, чтобы данные соответствовали/работали.

Нажав ‘Да», мы доберемся до конца нашей истории и наших данных!

Шаг 7: Посмотрите, Что сработало, а Что нет

Во-первых, есть ли плохие новости?

Если были строки, отклоненные базой данных, мы увидим их сейчас.

За этим диалогом находятся инструкции INSERT, которые мы пытались запустить, но не сработали. Вы можете изменить их вручную, чтобы исправить несколько записей. Но если у вас тысячи забракованных строк – лучше разобраться в файле (в источнике импорта).

Теперь давайте посмотрим на наши новые табличные данные!

Я люблю сладкий запах данных по утрам!

Обратите внимание на панель «Журнал» (Log). Там можно увиеть файл, с которым мы работали, и сколько времени потребовалось для загрузки данных.

Всё! Можно выдохнуть свободно. Импорт из файла Excel в таблицу базы данных Oracle завершен. В шапке статьи вы можете посмотреть видео инструкцию  — копию этого мануала на английском языке.

Вас заинтересует / Intresting for you:

convert your excel file format to .csv format with using save as option

Save below content in a file with .ctl extension in the D drive under folder_name folder. Before running this .ctl make sure that table should be present in your schema with the distinct column names not like in your posted image. And the column name should be match with names of .ctl file(sc_id,
sal, etc). And the datatypes of your columns should be match with the data present in a .csv file. And also make sure that your table should be empty otherwise you should use truncate or append options in your .ctl file.

 LOAD DATA
    INFILE 'D:folder_namecsvfile_name.CSV'
    BADFILE 'D:folder_namecsvfile_name.BAD'
    DISCARDFILE 'D:folder_namecsvfile_name.log'
    logfile 'D:folder_namecsvfile_name.DSC'
    iNTO TABLE schema_name.table_name
    FIELDS TERMINATED BY ','
    TRAILING NULLCOLS

    (
    sc_id,
    sal,
    sc_cd1,
    coll,
    sc_cd2,
    bill_mas,
   sc_cd3,
   wk_sal,
   check_bill_month,
   check_sale_wk
    ) 

Run your .ctl file in sql plus with use of below commands

sqlldr schema_name/password@databasename control=your control file path.

If any error occurs while loading data into table those will logged into .log file. For learn more about sqlloader Refer http://docs.oracle.com/cd/B10501_01/server.920/a96652/ch05.htm

In this oracle tutorial, we will learn how to connect excel to an oracle database. also, we will cover these topics.

  • Connect Excel to Oracle Database
  • Connect Excel to Oracle Database 12c
  • Excel Connect to Oracle Database without ODBC
  • Excel Connect to Oracle Database with ODBC
  • Excel Connect to Oracle Database using OLED
  • Excel Connection String to Oracle Database
  • Can you link excel to Oracle Database

In this section, we will learn how to connect Excel to Oracle Database without ODBC.

  • Microsoft Excel has built-in feature of connecting excel to oracle database and we show show you how to use it.
  • Once the connection is established, you will be able to access all the files in the oracle database of that common particular user.
  • In our case, c##sqlserverguides is the name of our common user name. Please note that it is mandatory to c## as suffix while creating a user name.
  • There are three things required to connect excel with the oracle database.
    • Server or SSID
    • Username
    • Password
  • Default ssid is “orcl” which is also the Global Database name. In case you have changed it or created a new one then please mention that one.
  • Open Microsoft Excel and click on the Data tab, from there click on the the From Database dropdown and select ‘From Oracle Database‘.
Connect Excel to Oracle Database
Connect Excel to Oracle Database
  • If you encounter this error then simply click on the on the OK button. The error won’t create problem while connecting excel with the Oracle database.
Oracle.DataAccess.Client is not Installed
  • Enter the name of server or ssid here. ssid is the name of the global database created at the time of installation. In our case, it is ‘orcl’, click on the ok button to proceed.
Enter Server or SSID to connect excel with oracle database
Enter Server or SSID to connect excel with oracle database
  • Excel is connected to oracle database now you can browse of all the oracle data on the microsoft excel.
Excel Connected to Oracle Database

Read How to Check Oracle Database Version

Connect Excel to Oracle Database with ODBC

In this section, we will learn how to connect excel to the oracle database on the windows operating system.

  • Offline installed Excel software can only be connected to the oracle database. Web based excel won’t give option to connect with the database.
  • First step in the process is we have to create a new data source on “Windows Administrative Tools” on windows operating system.
windows administrative tools
Windows Administrative Tools
  • Inside “Windows Administrative Tool” click on the ODBC Data Sources (64-bit). From the appeared prompt select “User DSN” tab and click on Add button.
  • Another prompt will appear “Create New Data Source” in that prompt select “Oracle in OraDB19Home1“. This name may change in future but it will always start with the key ‘oracle’. Click on the the finish button.
create new data source
Create New Data Source
  • Once you clicked on the finish button in the previous option, you will see “Oracle Database Driver Configuration” window.
  • Data Source Name: Name provided here will reflect in excel and you have to choose it over there.
  • Description: If you want to add a little description about your database you can write it here. Description can also be treated as instruction for other users of the database.
  • TNS Service Name: ‘orcl’ is the global database configured while installing the Oracle databse software. Incase you have changed it or created a new one then mention that here.
  • User ID: It is optional to provide user id. You can mention the common username here.
  • Click on the “Test Connection” button and provide the username and password and click on the ok button. If a prompt appear “Test Successful” that means you can move to next step now. Click on the Ok button on the “Oracle ODBC Driver Configuration” window.
oracle odbc driver connect
Oracle ODBC Driver Connect
  • Open Microsoft Excel and click on the Data tab, from there click on the the Get Data dropdown and select ‘From Other Sources‘, click on the option “From ODBC“.
Connect Excel to Oracle Database
Connect Excel to Oracle Database
  • Select the Data Source Name that we created in Oracle Odbc Driver Configuration.
  • Once done, it will ask for the username and password. Enter the credential and you will see that a screen with Navigation title will appear and now you can browse your data there. This is how we can connct excel with oracle database.
select database from ODBC in oracle database

Read How to Get List all Tables in Oracle Database

Connect Excel to Oracle Database 12c

In this section, we will learn how to connect excel to oracle database 12c on the windows operating system.

  • Oracle has released various versions so far out of these 12c and 11g were most popular and widely used versions.
  • Current stable long term version is Oracle database 19c and 21c is in innovation mode.
  • Though 12c has been obsolete still many organisations are still using it.
  • Steps to connect excel to oracle database 12c is similar to oracle database 19c. So you can follow section section “Connect Excel to Oracle Database with ODBC” of this tutorial.

Read: How to create table in Oracle

Excel Connect to Oracle Database without ODBC

In this section, we will learn how to connect excel connect to the oracle database without ODBC on the windows operating system.

  • Most of the connection between microsoft excel and oracle database are established using ODBC.
  • This type of connections are established in previous versions of microsoft excel when there was no option for from connecting oracle directly with excel.
  • In new versions there is already option to connect with oracle database as you can see in the below image.
from oracle database option in excel
From Oracle Database Option in Excel
  • In case this option is not available then using oled you can connect with the database.
  • to see practical implementation of excel connect to oracle database with oled visit the first section of this tutorial ” Connect Excel to Oracle Database”.

Also, check: How to Fetch Data from Oracle Database in Python

Excel Connect to Oracle Database using OLED

In this section, we will learn how excel connects to an oracle database using OLED in the Microsoft Windows operating system.

  • Open Microsoft Excel and click on the Data tab, from there click on the the Get Data dropdown, now click on ‘From Other Sources‘ and select From OLEDB.
excel connect to oracle using oled
Excel Connect to Oracle Database using OLED
  • In the connection string prompt enter the below code. In our case ‘orcl’ is the name of our global database so we have set source=orcl.
provider=OraOLEDB.Oracle.1;data source=orcl
  • After entering the above code click on the build button a new promot will appear “Data Link Properties”. Enter the user name and password for the user you want to connect with. In our case we are connecting with “c##sqlserverguides”.
  • Once filled all the required information (username & password) click on “Test connection” button. If Test connection succeeded click on ok for all the three screens.
microsoft data link to excel connect with oracle database using oled
Microsoft Data Link
  • New prompt will appear immedietly after clicking on ok button of “From OLE
    DB” window.
  • Enter username and password one last time and click on connect. It may take few seconds then excel will be connected to oracle database.
final step excel connect to oracle database using oled
Final Step: Excel Connect to Oracle Database using OLED
  • Below is the window that will appear on the successful establishment of the connection. You will be able to access all the files, folder and tables available inside the connected user.
Excel Connected to Oracle Database
Excel Connected to Oracle Database

Read: Oracle get database name

Excel Connection String to Oracle Database

In this section, we will learn how to establish an excel connection string to an oracle database.

  • While connecting excel to oracle database you must have noticed ‘Credential Connection String’ box that might be optional in some cases.
  • Excel Connection String holds all the information about the connecting database like host, hostname, port, IP address, server type and service name.
  • while connecting excel to oracle database using oled we have to provide excel connection string that you can us the below excel connection string to connect with oracle databse.
provider=OraOLEDB.Oracle.1;data source=orcl
  • If you are advance user and want to connect via oracle database on server than you can configure the setting using the below code.
provider=OraOLEDB.Oracle.1;data source=
             ("
              DESCRIPTION = 
                 (ADDRESS = 
                   (PROTOCOL = TCP)
                   (HOST = localhost)
                   (PORT = 1521)
                 ) 
              (CONNECT_DATA = 
                  (SERVER = DEDICATED) 
                  (SERVICE_NAME = orcl))
              )"

Can you link excel to Oracle Database

In this section, we will answer the question “can you link excel to the oracle database“.

  • Yes, we can link excel to oracle database and there are multiple ways of doing that.
  • In this tutorial, we have explained 3 mojor ways that are widely used to connect excel to oracle database.
    • Connect excel to oracle database
    • Excel Connect to Oracle Database with ODBC
    • Excel Connect to Oracle Database using OLED
  • Visit each section to learn more about how to connect excel with oracle database.

In this tutorial, we have learned how to connect excel to an oracle database. Also, we have covered these topics.

  • Connect Excel to Oracle Database
  • Connect Excel to Oracle Database 12c
  • Excel Connect to Oracle Database without ODBC
  • Excel Connect to Oracle Database using OLED
  • Excel Connection String to Oracle Database
  • Can you link excel to Oracle Database

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

I’ve been thinking about it for quite a long time and never really had time to implement it, but it’s finally there : a pipelined table interface to read an Excel file (.xlsx) as if it were an external table.

It’s entirely implemented in PL/SQL using an object type (for the ODCI routines) and a package supporting the core functionalities.
Available for download on GitHub :

/mbleron/ExcelTable

Usage

ExcelTable.getRows table function :

This is the actual SQL interface, to be used in conjunction with the TABLE operator.
It returns an ANYDATASET instance whose structure is defined by the p_cols parameter.

  function getRows (
    p_file   in  blob
  , p_sheet  in  varchar2
  , p_cols   in  varchar2
  , p_range  in  varchar2 default null
  ) 
  return anydataset pipelined
  using ExcelTableImpl;
Arg Data type Desc Mandatory
p_file BLOB Input Excel file in Office Open XML format (.xlsx or .xlsm).
A helper function (ExcelTable.getFile) is available to directly reference the file from a directory.
Yes
p_sheet VARCHAR2 Worksheet name Yes
p_cols VARCHAR2 Column list (see specs below) Yes
p_range VARCHAR2 Excel-like range expression that defines the table boundaries in the worksheet (see specs below) No

Range syntax specification

 range_expr ::= ( cell_ref [ ":" cell_ref ] | col_ref ":" col_ref | row_ref ":" row_ref )
 cell_ref   ::= col_ref row_ref
 col_ref    ::= { "A".."Z" }
 row_ref    ::= integer

If the range is empty, the table implicitly starts at cell A1.

Otherwise, there are four ways to specify the table range :

  • Range of rows : '1:100'
    In this case the range of columns implicitly starts at A.
  • Range of columns : 'B:E'
    In this case the range of rows implicitly starts at 1.
  • Range of cells (top-left to bottom-right) : 'B2:F150'
  • Single cell anchor (top-left cell) : 'C3'

Columns syntax specification

The syntax is similar to the column list in a CREATE TABLE statement, with a couple of specifics :

 column_list    ::= column_expr { "," column_expr }
 column_expr    ::= ( identifier datatype [ "column" string_literal ] | identifier for_ordinality )
 datatype       ::= ( number_expr | varchar2_expr | date_expr | clob_expr )
 number_expr    ::= "number" [ "(" ( integer | "*" ) [ "," [ "-" ] integer ] ")" ]
 varchar2_expr  ::= "varchar2" "(" integer [ "char" | "byte" ] ")"
 date_expr      ::= "date" [ "format" string_literal ]
 clob_expr      ::= "clob"
 for_ordinality ::= "for" "ordinality"
 identifier     ::= """ { char } """
 string_literal ::= "'" { char } "'"

Column names must be declared using a quoted identifier.

Supported data types are :

  • NUMBER – with optional precision and scale specs
  • VARCHAR2 – including CHAR/BYTE semantics
    Values larger than the maximum length declared are silently truncated and no error is reported.
  • DATE – with optional format mask
    The format mask is used if the value is stored as text in the spreadsheet, otherwise the date value is assumed to be stored as date in Excel’s internal serial format.
  • CLOB

A special “FOR ORDINALITY” clause (like XMLTABLE or JSON_TABLE’s one) is also available to autogenerate a sequence number.

Each column definition (except for the one qualified with FOR ORDINALITY) may be complemented with an optional “COLUMN” clause to explicitly target a named column in the spreadsheet, instead of relying on the order of the declarations (relative to the range).
Positional and named column definitions cannot be mixed.

For instance :

  "RN"    for ordinality
, "COL1"  number
, "COL2"  varchar2(10)
, "COL3"  varchar2(4000)
, "COL4"  date           format 'YYYY-MM-DD'
, "COL5"  number(10,2)
, "COL6"  varchar2(5)
  "COL1"  number        column 'A'
, "COL2"  varchar2(10)  column 'C'
, "COL3"  clob          column 'D'

Examples

Using this sample file :

1- Loading all six columns, starting at cell A2, in order to skip the header :

SQL> select t.*
  2  from table(
  3         ExcelTable.getRows(
  4           ExcelTable.getFile('TMP_DIR','ooxdata3.xlsx')
  5         , 'DataSource'
  6         , ' "SRNO"    number
  7           , "NAME"    varchar2(10)
  8           , "VAL"     number
  9           , "DT"      date
 10           , "SPARE1"  varchar2(6)
 11           , "SPARE2"  varchar2(6)'
 12         , 'A2'
 13         )
 14       ) t
 15  ;

      SRNO NAME              VAL DT                  SPARE1 SPARE2
---------- ---------- ---------- ------------------- ------ ------
         1 LINE-00001 66916.2986 13/10/1923 11:45:52
         2 LINE-00002 96701.3427 05/09/1906 10:12:35
         3 LINE-00003 68778.8698 23/01/1911 09:26:22        OK
         4 LINE-00004  95110.028 03/05/1907 13:52:30        OK
         5 LINE-00005 62561.5708 04/04/1927 18:10:39
         6 LINE-00006 28677.1166 11/07/1923 15:10:59        OK
         7 LINE-00007 16141.0202 20/11/1902 02:02:24
         8 LINE-00008 80362.6256 19/09/1910 14:06:42
         9 LINE-00009 10384.1973 16/07/1902 04:54:12
        10 LINE-00010  5266.9097 08/08/1921 11:51:34
        11 LINE-00011 12513.0679 01/07/1908 21:53:55
        12 LINE-00012 66596.9707 22/03/1913 05:20:10

...

        95 LINE-00095 96274.2193 08/04/1914 22:48:31
        96 LINE-00096  29783.146 06/04/1915 23:49:23
        97 LINE-00097 19857.7661 16/02/1909 21:21:52
        98 LINE-00098 19504.3969 05/12/1917 01:56:05
        99 LINE-00099 98675.8673 05/06/1906 17:41:10
       100 LINE-00100 24288.2885 22/07/1920 13:25:59

100 rows selected.

2- Loading columns B and F only, from rows 2 to 10, with a generated sequence :

SQL> select t.*
  2  from table(
  3         ExcelTable.getRows(
  4           ExcelTable.getFile('TMP_DIR','ooxdata3.xlsx')
  5         , 'DataSource'
  6         , q'{
  7             "R_NUM"   for ordinality
  8           , "NAME"    varchar2(10) column 'B'
  9           , "SPARE2"  varchar2(6)  column 'F'
 10           }'
 11         , '2:10'
 12         )
 13       ) t
 14  ;

     R_NUM NAME       SPARE2
---------- ---------- ------
         1 LINE-00001
         2 LINE-00002
         3 LINE-00003 OK
         4 LINE-00004 OK
         5 LINE-00005
         6 LINE-00006 OK
         7 LINE-00007
         8 LINE-00008
         9 LINE-00009

9 rows selected.

Содержание

  1. Odie’s Oracle Blog
  2. XML & JSON functionalities in the database, and related stuff…
  3. Oracle SQL – Reading an Excel File (xlsx) as an External Table
  4. Usage
  5. Range syntax specification
  6. Columns syntax specification
  7. Examples
  8. Share this:
  9. Like this:
  10. Related
  11. 30 thoughts on “ Oracle SQL – Reading an Excel File (xlsx) as an External Table ”
  12. Leave a Reply Cancel reply
  13. Русские Блоги
  14. PL / SQL ODBC Импорт Excel в Oracle

Odie’s Oracle Blog

XML & JSON functionalities in the database, and related stuff…

Oracle SQL – Reading an Excel File (xlsx) as an External Table

I’ve been thinking about it for quite a long time and never really had time to implement it, but it’s finally there : a pipelined table interface to read an Excel file (.xlsx) as if it were an external table.

It’s entirely implemented in PL/SQL using an object type (for the ODCI routines) and a package supporting the core functionalities.
Available for download on GitHub :

Usage

ExcelTable.getRows table function :

This is the actual SQL interface, to be used in conjunction with the TABLE operator.
It returns an ANYDATASET instance whose structure is defined by the p_cols parameter.

Arg Data type Desc Mandatory
p_file BLOB Input Excel file in Office Open XML format (.xlsx or .xlsm).
A helper function ( ExcelTable.getFile ) is available to directly reference the file from a directory.
Yes
p_sheet VARCHAR2 Worksheet name Yes
p_cols VARCHAR2 Column list (see specs below) Yes
p_range VARCHAR2 Excel-like range expression that defines the table boundaries in the worksheet (see specs below) No

Range syntax specification

If the range is empty, the table implicitly starts at cell A1.

Otherwise, there are four ways to specify the table range :

Range of rows : ‘1:100’
In this case the range of columns implicitly starts at A.

Range of columns : ‘B:E’
In this case the range of rows implicitly starts at 1.

  • Range of cells (top-left to bottom-right) : ‘B2:F150’
  • Single cell anchor (top-left cell) : ‘C3’
  • Columns syntax specification

    The syntax is similar to the column list in a CREATE TABLE statement, with a couple of specifics :

    Column names must be declared using a quoted identifier.

    Supported data types are :

      NUMBER – with optional precision and scale specs

    VARCHAR2 – including CHAR/BYTE semantics
    Values larger than the maximum length declared are silently truncated and no error is reported.

    DATE – with optional format mask
    The format mask is used if the value is stored as text in the spreadsheet, otherwise the date value is assumed to be stored as date in Excel’s internal serial format.

    A special “FOR ORDINALITY” clause (like XMLTABLE or JSON_TABLE’s one) is also available to autogenerate a sequence number.

    Each column definition (except for the one qualified with FOR ORDINALITY) may be complemented with an optional “COLUMN” clause to explicitly target a named column in the spreadsheet, instead of relying on the order of the declarations (relative to the range).
    Positional and named column definitions cannot be mixed.

    Examples

    Using this sample file :

    1- Loading all six columns, starting at cell A2, in order to skip the header :

    2- Loading columns B and F only, from rows 2 to 10, with a generated sequence :

    Like this:

    30 thoughts on “ Oracle SQL – Reading an Excel File (xlsx) as an External Table ”

    This is an excellent piece of work on so many levels. The grammar for mapping types is excellent.

    Odie,
    I am trying to use your, Code for a POC, but I am stuck at the point in the oox_install.sql Script where there ina Anonymous Block,
    declare
    res boolean;
    begin
    res := DBMS_XDB.createFolder(‘/office’);
    res := DBMS_XDB.createFolder(‘/office/excel’);
    res := DBMS_XDB.createFolder(‘/office/excel/conf’);
    res := DBMS_XDB.createFolder(‘/office/excel/temp’);
    res := DBMS_XDB.createFolder(‘/office/excel/docs’);
    end;
    /

    I am getting the Following Error
    [Error] Execution (77: 1): ORA-31050: Access denied
    ORA-06512: at “XDB.DBMS_XDB”, line 340
    ORA-06512: at line 4

    I requested my DBA to Provide XDBADMIN to my schema, still the Same.

    What could be wrong.?

    Seems like you want to use the demo from this post : https://odieweblog.wordpress.com/2012/01/28/xml-db-events-reading-an-open-office-xml-document-xlsx/
    yet you’re posting your comment in another post.
    What do you want to do?
    Try EXCELTABLE package instead.

    Odie,
    Thanks for your Reply, I apologize for posting this Comment in the Wrong window, I had Opened Almost All your XML + Reading Excel file related article pages in my browser.

    The solution sounds promising, but I followed your installation steps on GitHub, and I got following compilation errrors for “ExcelTable.pkb”:

    Error(979,3): PL/SQL: Item ignored
    Error(989,3): PLS-00311: the declaration of “db.office.spreadsheet.ReadContext.initialize(java.sql.Blob, java.sql.Blob, java.lang.String, int, int, int) return int” is incomplete or malformed
    Error(992,3): PL/SQL: Item ignored
    Error(995,3): PLS-00311: the declaration of “db.office.spreadsheet.ReadContext.iterate(int, int) return java.sql.Array” is incomplete or malformed
    Error(998,3): PL/SQL: Item ignored
    Error(1000,3): PLS-00311: the declaration of “db.office.spreadsheet.ReadContext.terminate(int)” is incomplete or malformed

    What’s your database version? (select * from v$version)

    Very useful package, thanks for sharing. I was trying to use as part of an ETL process written in PL/SQL. I have the call to your package within a cursor. When I run the SQL bit as SQL it works fine. But when I try to compile the exact same SQL but in a PL/SQL cursor (cursor xyz is select … from table(exceltable.getrows….) I get ORA-22905, cannot access rows from a non-nested table item. Any clues? Thanks again.

    Hi Robert, thanks for your feedback.
    It is a known error (unfortunately) when trying to use table functions returning AnyDataset within PL/SQL.
    Apparently, Oracle is not able to call the ODCITableDescribe routine at compile time and therefore cannot retrieve the projection from the SELECT statement.
    The workaround is to use dynamic SQL :
    OPEN my_refcursor FOR ‘SELECT . ‘ USING

    Thanks for feedback – that’s exactly how I got around the issue. Good to know I’m not totally stupid 🙂

    FYI, in ExcelTable 1.4, I’ve added a new function getCursor() with same parameters as getRows() and returning a REF cursor.

    The solution seems to have everything we need for our problem. I just have one question. Our Excel files are stored in a table as BLOB. Can you please post an example how getRows() can be used with BLOB?

    That’s easy. Just pass your BLOB column to the p_file parameter :

    Hi, this is excellent work. Could you provide an example using getCursor() fetched into a record variable? Thanks.

    Hello. I’m trying to use your code with example 1 to test but I can’t run it. Surely a mistake from my side, but i don’t find the clue …
    Directory created and granted sur my user REF
    file ooxdata3.xlsx exists and test of function getfile is OK

    select t.*
    from table(
    ExcelTable.getRows(
    ExcelTable.getFile(‘TMP_DIR’,’ooxdata3.xlsx’)
    , ‘DataSource’
    , ‘ “SRNO” number
    , “NAME” varchar2(10)
    , “VAL” number
    , “DT” date
    , “SPARE1” varchar2(6)
    , “SPARE2” varchar2(6)’
    , ‘A2’
    )
    ) t
    ;

    return a PLS-00225 : line 4 col 6 subprogram of cursor ‘REF’ is out of scope.

    I’m on oracle 11.2.0.3 x64 and windows 2008 R2 … All is well compiled, I don’t know where to search.

    I’ve done another test on oracle 12c and it works.

    Hello. I’m trying to use your code with example 1 to test but I can’t run it.

    select t.*
    from table(
    ExcelTable.getRows(
    ExcelTable.getFile(‘TMP_DIR’,’ooxdata3.xlsx’)
    , ‘DataSource’
    , ‘ “SRNO” number
    , “NAME” varchar2(10)
    , “VAL” number
    , “DT” date
    , “SPARE1” varchar2(6)
    , “SPARE2” varchar2(6)’
    , ‘A2’
    )
    ) t
    ;

    return ORA-00955: name is already used by an existing object al line 1121 in EXCELTABLE object.
    At line 1121 your code tries to create a global temporary table.
    WHat can i do?
    Thanks

    How can we use This query inside SP or PL/SQL block? I get error always cannot access rows from non-nested table

    It’s explained in one of the comments above : use dynamic SQL, or ExcelTable.getCursor() if you want to use the query in a cursor (see the README).

    Great work. It helped me a lot. Thank you for sharing.
    It’s working nicely for small file for me but
    while inserting a large excel file 200000 rows into oracle table, I getting
    insert /+APPEND/ into REASSIGNMENT_tmp
    *
    ERROR at line 1:
    ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00664: VM Node-Stack overflow.
    ORA-06512: at “XDB.DBMS_XSLPROCESSOR”, line 743
    ORA-06512: at “XDB.DBMS_XSLPROCESSOR”, line 771
    ORA-06512: at “HARI.EXCELTABLE”, line 1760
    ORA-06512: at “HARI.EXCELTABLE”, line 1862
    ORA-06512: at “HARI.EXCELTABLE”, line 2295
    ORA-06512: at “HARI.EXCELTABLEIMPL”, line 60
    ORA-06512: at line 1

    Please advice;
    2) I need to commit every 10000 record, what method you suggest ?

    For large files, you’ll have to use the streaming read method (requires Java).
    See the README for instructions, and this post.

    About your other question, I’ve never understood the need for any “COMMIT every N record” requirement.
    Anyway, it’s not possible with a single INSERT/SELECT statement, let alone with the APPEND hint.
    I suggest you use the cursor-based approach. See procedure ExcelTable.getCursor() and insert in a loop, then you’ll be able to implement your commit-every stuff.

    How we have to specify the Boolean data type

    What do you mean? Boolean data type from Excel?

    I am trying to create a materialized view from the select of the table. The direct select works fine, but when I place into the materialized view the it only takes the first column (for each column …

    Has Anyone come across this issue? is there a way to resolve?
    Is there something in my code I could use to fix this?

    In the following example, the Materialized view give the value of the row_number in each column…

    SELECT xl.*
    FROM TABLE (IDATA.PAK_ExcelTable.F_getRows (
    IDATA.PAK_ExcelTable.F_getFile (‘IDATA_DATA’, ‘EMIDB.XLSX’),
    ‘Sheet1’,
    ‘”ROW_NUMBER” for ordinality
    , “OPEN_INCIDENT_FLAG” varchar2(5) column ”A”
    , “BAND_NUMBER” number(10, 0) column ”B”
    , “EMAP_ELIGIBLE_FLAG” varchar2(1) column ”C”
    , “MAIN_CATEGORY” varchar2(5) column ”D”’,
    ‘A2’)) xl;

    ROW_NUMBER OPEN_INCIDENT_FLAG BAND_NUMBER EMAP_ELIGIBLE_FLAG MAIN_CATEGORY

    CREATE MATERIALIZED VIEW BB_TEST (ROW_NUMBER,OPEN_INCIDENT_FLAG,BAND_NUMBER,EMAP_ELIGIBLE_FLAG,MAIN_CATEGORY)
    BUILD IMMEDIATE
    REFRESH FORCE ON DEMAND
    WITH PRIMARY KEY
    AS
    /* Formatted on 8/15/2018 11:52:16 AM (QP5 v5.269.14213.34746) /
    SELECT xl.

    FROM TABLE (IDATA.PAK_ExcelTable.F_getRows (
    IDATA.PAK_ExcelTable.F_getFile (‘IDATA_DATA’, ‘EMIDB.XLSX’),
    ‘Sheet1’,
    ‘”ROW_NUMBER” for ordinality
    , “OPEN_INCIDENT_FLAG” varchar2(5) column ”A”
    , “BAND_NUMBER” number(10, 0) column ”B”
    , “EMAP_ELIGIBLE_FLAG” varchar2(1) column ”C”
    , “MAIN_CATEGORY” varchar2(5) column ”D”’,
    ‘A2’)) xl;

    select * from bb_test
    ;
    ROW_NUMBER OPEN_INCIDENT_FLAG BAND_NUMBER EMAP_ELIGIBLE_FLAG MAIN_CATEGORY

    I can’t reproduce the problem. What’s your exact database version please?

    Hello, please help with the error:
    ORA-20722: Error at position 1 : unexpected symbol ” instead of ”
    ORA-06512: на “DWH.EXCELTABLE”, line 1041
    ORA-06512: на “DWH.EXCELTABLE”, line 1414
    ORA-06512: на “DWH.EXCELTABLE”, line 1427
    ORA-06512: на “DWH.EXCELTABLE”, line 1574
    ORA-06512: на “DWH.EXCELTABLE”, line 1585
    ORA-06512: на “DWH.EXCELTABLE”, line 1597
    ORA-06512: на “DWH.EXCELTABLE”, line 2688
    ORA-06512: на “DWH.EXCELTABLEIMPL”, line 16
    ORA-06512: на line 4

    select t.*
    from table(
    ExcelTable.getRows(
    ExcelTable.getFile(‘TMP_DIR’,’ooxdata3.xlsx’)
    , ‘DataSource’
    , ‘ “SRNO” number
    , “NAME” varchar2(10)
    , “VAL” number
    , “DT” date
    , “SPARE1” varchar2(6)
    , “SPARE2” varchar2(6)’
    , ‘A2’
    )
    ) t
    ;

    Hello,
    Just found this post and it’s exactly what I for my requirement. However, it seems the Excel file must be on the DB server for the store function to work, correct? How can we load the Excel file that reside on Window client since I don’t have access to the DB server? Thank you in advance,

    Hi, sorry for the late reply.
    You are correct, the file must reside in a location the DB server has access to, not necessarily the DB server itself though, could be a NFS (Network File System) for example.
    To address your situation, a classical approach is to mount a shared Windows directory on the DB server, so that end users may deposit files to be read by the DB.
    If such a setup is not possible, the only other option I see is to send the file to the server as a separate step (e.g. SFTP/FTP protocol), or directly load the file in a BLOB in a temp table using SQL*Loader, you’ll then be able to use ExcelTable over the BLOB.

    This is really cool Thank you for sharing.

    DATE type columns gave me some trouble initially, but turns out that was related to the header row not being a valid DATE format.

    Is there a good way to have this ignore the row of headers, specifically when the column needs to be DATE type?

    I just answered my own question. Adding ,’A2′ at the end of the selection, as you show in an example, will resolve the header situation.

    Leave a Reply Cancel reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Источник

    Русские Блоги

    PL / SQL ODBC Импорт Excel в Oracle

    1, войти в PL / SQL, нажмите [Инструменты] → [Importer ODBC].

    2, Откройте опцию [Данные из ODBC] → [User / System DSN] Выберите [Файлы Excel], [Имя пользователя] и [Пароль] Заполните пароль PL / SQL Войти Пароль учетной записи → Нажмите [Connect], выберите Excel для импорта , нажмите 【Определите】

    3, если [User / System DSN] не имеет опции [файлов Excel], вам нужно настроить DSN:

    3.1, нажмите [Пуск] → [Все программы] → [Oracle — ORADB10G_HOME1] → [Инструменты конфигурации и трансплантации] → [Microsoft ODBC Administrator]: Нажмите [Добавить] ниже [User DSN] или [System DSN]. Добавить Драйвер Microsoft Excel (*. XLS)] Драйвер DSN, [Имя источника данных] — [Файлы Excel]

    3.2, если вышеуказанная операция не находит [драйвер Microsoft Excel (*. XLS)] драйвер (например, Win7 Environment, Oracle10G), клики:

    C: Windows Syswow64 odbcad32.exe для конфигурации DSN

    4, затем вышеупомянутое 2, в [Import Table], выберите лист для импорта Excel, вы можете просмотреть данные в [Предварительный просмотр результатов]; затем нажмите кнопку «Данные в Oracle], [Владелец] Выберите пользователя, [Таблица] Выбрать Целевая таблица, [поля], [поле], [fieldtype] Сопоставьте столбец Excel с столбцом таблицы и, наконец, нажмите [Import] для завершения.

    Источник

    Like this post? Please share to your friends:
  • Oracle smart view excel
  • Oracle odbc driver 64 bit excel
  • Oracle external table excel
  • Oracle excel to database
  • Oracle add in for excel