Easily Import and Export Excel Data to SQL Server

Updated on March 5, 2019
klanguedoc profile image

Kevin is a Software Developer with 20 years experience designing and building business intelligence and system integration solutions.

Importing Data from MSSQL Server

Over the years Microsoft has greatly improved how Excel integrates with other databases, including of course, Microsoft SQL Server. Each version has seen many improvements in ease of functionality to the point where extracted data from many sources is as easy as it gets.

In this example, we will extract data from a SQL Server (2016) but this will equally well with other versions. Follow these steps to extract data:

From the Data tab click on the Get Data drop-down menu as shown in figure-1 below and select the From Database section and finally From SQL Server Database which will the display of an input panel to enter the server, database and credentials.


Select SQL Server for your data source
Select SQL Server for your data source | Source

The SQL Server database connection and query interface shown in figure-2 allows us to enter the name of the server and optionally the database where the data we need is stored. If you don’t specify the database, in the next step you will still need to select a database, so I highly recommend that you enter a database here to save yourself the extra steps. Either way, you will need to specify a database.

Enter connection details to connect the server
Enter connection details to connect the server | Source

Or, write a query by click on the Advanced options to expand the custom query section which is shown in figure-3 below. Although the query field is basic, meaning that you should use SSMS or another query editor to prepare your query if it is modestly complex or if you need to test it before using it here, you can paste in any valid T-SQL query that returns a result set. This means that you can use this for INSERT, UPDATE or DELETE SQL operations.

  • A couple of additional information regarding the three options under the query field. These are “Include relationship columns”, “Navigate full hierarchy” and “Enable SQL Server failover support”. Of the three I find the first one the most useful and is always enabled by default.

  • The “Include relationship columns” option will tell SQL Server to automatically include any columns in another table that has a relationship with any of the columns in the tables that are included in the query.
  • Navigate full hierarchy expands the tree view of the tables and columns that are included in the query
  • iii. Enable SQL Server failover support ensures that, in case, the server connection fails or if there are too many connections on one server, you the connection will automatically switch to another connection/server in the cluster. This option is only useful if you have a SQL Server farm that is configured as a cluster with failover.

Source

Export Data to Microsoft SQL Server

While it is very easy to extract data from a database like MSSQL, uploading that data is a bit more complicated. To upload to MSSQL or any other database, you either need to use VBA, JavaScript (2016 or Office365), or use an external language or script. The easiest in my opinion is to use VBA as it is self-contained in Excel.

Basically, you need to connect to a database, assuming of course you have “write” (insert) permission on the database and the table, then

  1. Write an insert query that will upload each row in your dataset (it is easier to define an Excel Table – not a DataTable).
  2. Name the table in Excel
  3. Attach the VBA function to a button, or macro


Source

Enable Developer Mode

Next, open the VBA editor from the Developer tab to add VBA code to select the dataset and upload to SQL Server.

Sub UploadToDatabase()
	Dim connection As ADODB.connection
	Dim command As ADODB.command
	Dim query As String
	Dim xlSheet As Worksheet
	Dim recordset As ADODB.recordset

	Set xlSheet = ActiveSheet

	'If you are using username and password (not your Windows login)
	'      connection.Open "Provider=SQLOLEDB;" & _
	'            "Data Source=The_Name_of_your_Server;" & _
	'            "Initial Catalog= Autzen2200;" & _
	'            "User ID=user1; 
	Password=pass1"

	'or

	'If you are using Windows login
	connection.Open "Provider=SQLOLEDB;" & _
	"Data Source=The_Name_of_your_Server;" & _
	"Initial Catalog= Autzen2200;" & _
	"Integrated Security=SSPI;"

	query = "INSERT INTO your_SQL_table_name " & _
	"SELECT * from your_excel_table_name "

	If connection.State = adStateOpen Then
	command.CommandType = adCmdText
	command.CommandText = query

	command.ActiveConnection = connection

	' Execute once and display...
	'Set recordset = command.Execute
	' OR with no result set
	command.Execute
	End If

	recordset.Close
	connection.Close
	Set connection = Nothing
	Set command = Nothing
	Set recordset = Nothing
End Sub

Note:

Query = “INSERT INTO your_SQL_table_name” & _ “SELECT * from your_excel_table_name ”

Using this method, while easy, assumes that all the columns (count and names) match the number of columns in your database table and have the same names. Otherwise you will need to list the specific column names, like:

Query = “INSERT INTO your_SQL_table_name (column1, column2, column3, etc.)” & _

“SELECT column1, column2, column3 from your_excel_table_name”

If the table doesn’t exist, you can export the data and create the table using one simple query as the following:

Query = “SELECT * INTO your_new_table FROM excel_table_name”

Or

Query = “SELECT col1, col2, col3 INTO your_new_table FROM excel_table_name”

The first way, you create a column for every column in the excel table. The second option allows you to select all the columns by name or a subset of the columns from the Excel table.

These techniques are the very basic way to import and export data to Excel. Creating tables can get more complicated if you can to add primary keys, indexes, constraints, triggers and so on but is another subject.

This design pattern can be used for other databases as well like MySQL or Oracle. You would just need to change the driver for the appropriate database.

This article is accurate and true to the best of the author’s knowledge. Content is for informational or entertainment purposes only and does not substitute for personal counsel or professional advice in business, financial, legal, or technical matters.

© 2019 Kevin Languedoc

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)