How to load xls/xlsx file to MSSQL database using SQL code

Posted by

To load data from an Excel (.xls or .xlsx) file into a Microsoft SQL Server (MSSQL) database, you can use SQL Server’s built-in functionality called “SQL Server Import and Export Wizard” or the “BULK INSERT” statement. I’ll walk you through both methods:

Method 1: SQL Server Import and Export Wizard:

  1. Open SQL Server Management Studio (SSMS) and connect to your MSSQL server.
  2. Right-click on the database where you want to import the data and select “Tasks” > “Import Data…”
  3. In the “Choose a Data Source” window, select “Microsoft Excel” as the data source and browse to the location of your Excel file.
  4. Follow the wizard’s instructions to select the Excel sheet and configure the settings for importing data, such as data type conversions and destination table.
  5. Once the import is configured, click “Next” and review the summary. Click “Finish” to start the import process.

Method 2: BULK INSERT SQL Statement:

If you prefer to use SQL code to load the data, you can use the “BULK INSERT” statement. However, similar to the previous method, you need to save the Excel data as a CSV file first.

  1. Save the Excel file as a CSV file. Make sure to use commas as the delimiter.
  2. Ensure that the SQL Server service account has access to read the CSV file.
  3. Use the following SQL code to load the CSV data into the MSSQL table:
BULK INSERT your_table_name
FROM 'C:\Path\To\Your\CSV\File.csv'
WITH (
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n',
    FIRSTROW = 2 -- If the CSV file contains a header row, use FIRSTROW = 2 to skip it
);

Replace your_table_name with the name of the MSSQL table where you want to load the data. Ensure that the table structure matches the CSV data columns in the correct order.

The FIELDTERMINATOR specifies the delimiter used in the CSV file. In this case, it’s a comma (,).

The ROWTERMINATOR indicates the line termination character in the CSV file. The default value is ‘\n’, which is used for newline. If your CSV file has a different line termination character, update it accordingly.

The FIRSTROW specifies the starting row for importing data. If your CSV file has a header row, use FIRSTROW = 2 to skip it.

  1. Execute the SQL code to perform the bulk insert operation.

Both methods allow you to load data from Excel files into a MSSQL database efficiently. Choose the method that best suits your preference and requirements.