SQL Server Export/Import excel using R script

In this post, let us see new approach to import excel into SQL Server and export SQL server data to excel. There are some existing methods to do this using BCP, Bulk Insert, Import & Export wizard from SSMS, SSIS, Azure data factory, Linked server & OPENROWSET query and SQLCMD.

BULK INSERT statement, the BCP tool, or Azure Data Factory can't read Excel files directly
BCP - Work around has to be done to include the header  
SSIS - With dynamic source & destination, handling mapping increases the complexity of the package
SQLCMD - Cannot export output in Excel

R & Python language extension was introduced in SQL Server 2016 & 2017 as part of machine learning. With support of R in Azure SQL database and Java language extension support in SQL Server 2019, this new approach can be used extensively as it easy, fast and flexible.




Below series of posts has some examples on how to install various R packages (xlsx - read/write excel & readxl - used for reading excel). 

Also I have showed examples on: 

i) how to export SQL Server data into excel file with multiple tabs with table names as sheet names

ii) how to export SQL Server data into multiple excel files with table name as file & sheet names

iii) how to import excel with multiple sheets into different SQL Server table by creating target schema dynamically with sheet name as table name

iv) how to import multiple excel files in a directory (including sub folders) with multiple sheets into different SQL Server table by creating target schema dynamically with file name + sheet name as table name

v) how to export output of SQL files stored in a folder to excel files


SQL Server Export/Import excel using R script - Part 1
SQL Server Export/Import excel using R script - Part 2
SQL Server Export/Import excel using R script - Part 3
SQL Server Export/Import excel using R script - Part 4
SQL Server Export/Import excel using R script - Part 5
SQL Server Export/Import excel using R script - Part 6

Above examples are done using the base R packages & functions and very few are explicitly installed to achieve some excel operations.

With respect to moving data (Import / Export) between SQL Server & Excel, there are various scenarios based on each requirement. I have covered some of them but tweaking the solutions mentioned above can cover any scenario.

I'll keep updating this article with different examples. If anyone has specific requirement or any issues trying above examples, please comment.

See Also:

SQL Server export adhoc SQL or table to CSV file
Import csv or text file into SQL Server table

No comments: