Export query results to excel

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

Export SQL Data to Excel from Microsoft SQL Server

Let’s go over three ways to export an SQL Query to an Excel File Using MSSQL 

Despite the pushback from Database aficionados, sometimes it makes sense to export data from SQL to an Excel file. It really depends on who is the audience of the information. Not everyone is great with SQL Analysis. Few people require access to the database.

And lots of times the boss just needs to see the information in Excel.

So, if Excel is the Output required this article is here to help you Export SQL Queries to Excel. 

Here are three ways to Export a SQL query to Excel format. The last one can be kind of tricky. I’ll provide a condensed version followed by a detailed version with screenshots.

Three quick ways to Export SQL Data to Excel:

Choose the Summarized Version and then scroll to further down to use the SQL Export Version to Excel that works best for you. 

Educative

Method Number 1 – Copy Grid results and Paste into Excel

Under Query, Make sure results to Grid are selected.
After Running your query, right-click the top right corner of the grid.
Copy With Headers.
Paste into an Excel File

Possible Issues:
I’ve seen formatting issues with this strategy. For Example, there are situations where the spreadsheet drops preceding zeroes after the copy-paste.

I’ve also noticed lengthy fields, (think of a really long free text field) end up running into the next line.

For the reasons above, I prefer this next method for a clean Excel file.

Method Number 2: Export the Query Results as a Task

In the object explorer window, find the database you want to export from.
Right Click the Database, Click Tasks, and Export Data
The Wizard walks you through the rest of the steps but I have included screenshots below.

Method Number 3 – Use Good Old fashioned TSQL to send the data to an excel file

For those who value speed above all use the following script format.

INSERT INTO OPENROWSET(‘Microsoft.ACE.OLEDB.12.0′,’Excel 12.0; Database=C:SQL2019ReportsUsernames.xlsx;’,’SELECT * FROM [Sheet1$]’) SELECT DisplayName FROM dbo.Users Where Reputation > 2000

Possible Issues – Configuring this might not be your type of fun and getting this straight deserves its own article.

Step by Step instructions with screenshots

keepersecurity.com

Method Number 1 – Copy Grid results and paste into Excel

After ensuring results to grid turned on, Execute your query, right-click the top left-hand corner of the results grid.

Copy Grid results and paste into Excel

Choose Copy with Headers and then you are ready to paste in Excel with Ctrl + C

Headers

Method 2 – Export Via the Export Wizard

Right-click on the database you want to export from. Then Select tasks and “Export Data”.

Export Data

The SQL Server Wizard will startup. Click Next through the prompts.

SQL Server Wizard

Select the appropriate Native client, your server name, and database and choose “Next”.

server name and database

Next, Select Microsoft Excel and the file path where you want to import the data. The .xls file that you name will be created by this process.

Microsoft Excel

Now you can choose to export a whole table or a query. For the purpose of this exercise, we are creating a query.

creating a query

Paste the query into the SQL Statement field. Make sure every output field has a unique name.

SQL Statement

Click Next on the “Select Source Tables and Views” screen.

Select Source Tables

I use the default settings on the “conversion issues and data type mapping screen”

data type mapping screen

Now you can choose to Run immediately or Save an SSIS Package for later reuse.

SSIS Package

Double Check your settings and click finish.

Make sure there were no errors in the Export.

Export Wizard

Now Go to the directory you choose earlier and make sure you have a sweet-looking Excel File at that location!

Excel File

Method Number 3 – Use TSQL to send the data to an excel file

This method is the quickest once you get it set up but the configuration is the tricky part. Permissions can be a limiting factor.

Also with the script below, you have to make sure the file exists before you run the query for it to import properly.

First, create a blank excel file at the directory of your choosing.

C:SQL2019ReportsUsernames.xlsx

Then run this script below.

INSERT INTO OPENROWSET(‘Microsoft.ACE.OLEDB.12.0’,’Excel 12.0;
Database=C:SQL2019ReportsUsernames.xlsx;’,’SELECT * FROM [Sheet1$]’)
SELECT DisplayName FROM dbo.Users Where Reputation > 2000

Configuring this can be tricky and dependent on your level of permissions. Make sure you have the correct Linked Server/Provider installed (‘Microsoft.ACE.OLEDB.12.0’) And check your Database user settings to this server .

Do you need to export your query output to an Excel file in SQL Developer?

If so, you’ll see the complete steps to accomplish this goal.

Step 1: Run your query

To start, you’ll need to run your query in SQL Developer. You can run any query based on your needs.

Step 2: Open the Export Wizard

Once you’re done running the query in SQL Developer, you’ll see the query output at the bottom of your screen.

Right-click on any cell on the query results, and then select the ‘Export…‘ option from the drop down menu.

You’ll then see the Export Wizard.

Step 3: Select the Excel format and the location to export your file

Now you’ll need to:

  1. Select the Excel format from the drop-down list. You can choose the xlsx format for recent versions of Excel, or the xls format for previous versions of Excel
  2. Click on the ‘Browse…‘ button to select the location where the Excel file will be saved
  3. Press on the ‘Next >‘ button once you are done

Step 4: Export the query output to Excel

For the final step, click on the ‘Finish‘ button to export the query output to Excel.

Conclusion

You just saw how to export your query output to Excel in SQL Developer. You can choose to export your query results to either the xlsx format for newer versions of Excel, or the xls format for previous versions of Excel.

If you need to export your query output to a CSV file, you may then check the following guide that explains the steps to export your query results to CSV in SQL Developer. Alternatively, you may apply spool to accomplish the same goal.

Содержание

  1. Export Data from SSMS to Excel
  2. Getting Query Results from SSMS to Excel
  3. Copy and Paste from Results Tab
  4. Save Results as a Delimited File
  5. Saving Results Directly to a Fixed-Width .rpt File
  6. Using the SQL Server Import and Export Wizard
  7. How to Export Data from SQL Server to Excel
  8. Download AdventureWorks Database
  9. Creation of Excel File from SQL Query using R
  10. Complete Code
  11. Make Excel File Name Dynamic
  12. Streamline and Separate R Code
  13. Conclusion
  14. Related Articles
  15. Popular Articles
  16. Comments For This Article

Export Data from SSMS to Excel

Problem

You’re running an ad-hoc query in a Microsoft SQL Server database with SQL Server Management Studio (SSMS) and need to further analyze the result set in an Excel spreadsheet. How do you export the data?

Solution

SSMS gives us a few options to get our results to Excel. As with most problems, there is more than one way to solve it so we’ll step through more than one solution that can all get us to the same place.

Getting Query Results from SSMS to Excel

These are the four methods of getting query results from SSMS to Excel we’ll be covering:

  1. Copy and paste from the results tab
  2. Save results as a delimited file
  3. Saving results directly to a fixed-width .rpt file
  4. Using the SQL Server Import and Export Wizard

You would likely be working with a lot more data than this, but in the interest of keeping the screenshots clean and readable, and focusing on the solution instead of the data, we’ll run the following T-SQL query in an SSMS Query Window to obtain a list of product names and models from the AdventureWorksLT2019 database.

Note: Examples were done with SSMS 18.11.1 which is the latest version as of this writing and Microsoft Excel for Microsoft 365.

Copy and Paste from Results Tab

This method requires the results to be sent to the default grid output. If the results are not going to the grid here is how to change it:

  1. Right-click in the Query Window
  2. Results To
  3. Results to Grid

Or simply Ctrl+D

To make the setting permanent

  1. Query Results
  2. SQL Server
  3. General
  4. Results to grids in the Default destination for results: dropdown

Okay, now we have our results going where we want them, we can quickly and easily get those results into Excel with a simple copy and paste. Note: you can also select a contiguous subset of the records but for this example, we’re presuming you’ve already filtered out what you want in the query.

  1. Click the box in the upper left-hand corner of the Results pane to highlight all records
  2. Click on Copy with Headers or Ctrl+Shift+C

Open a blank workbook in Excel

And your results are pasted in the workbook and ready for your analysis.

One annoyance you may run into is you paste your data into Excel and concatenates your columns and pastes everything into one column like this.

If this happens:

  1. Highlight the column
  2. Choose Data from the Ribbon
  3. Click Text to Columns

And the Text to Columns Wizard will open.

  1. Check the Tab box and be sure to uncheck any others
  2. Finish

Now each column is in its own Excel column where it belongs.

No need to save the change. Excel will remember it.

Save Results as a Delimited File

In addition to copying and pasting, SSMS also provides the ability to export the result set to either a comma delimited or tab delimited file that can be opened with Excel. Instead of highlighting and copying the results:

  1. Right-click in the Results window
  2. Save Results As…

  1. Select location to save the file
  2. Name file
  3. Select comma or tab delimited from Save as type dropdown
  4. Save

  1. Right-click file
  2. Open with and choose Excel

The file can now be saved as an Excel spreadsheet.

Saving Results Directly to a Fixed-Width .rpt File

Instead of a delimited file, we may want to work with a fixed-width file. SSMS also provides the functionality to output the results directly to a fixed-width file without going to the result pane.

  1. Right-click in Query Window
  2. Results To
  3. Results to File

Run the query and you’ll be presented with a dialog box.

  1. Select the folder where you want to save the file
  2. Give the file a name
  3. Save

Open the file in Excel.

This will open the Text Import Wizard.

  1. Fixed Width instead of the default of Delimited
  2. Uncheck My data has headers. If you don’t have headers
  3. Next

  1. Verify / edit break line(s)
  2. Next

  1. Change data type if you wish
  2. Finish

Save as a .xlsx file.

Using the SQL Server Import and Export Wizard

We can also use the built-in SQL Server Import and Export Wizard. The Import and Export Wizard is a tool that uses SQL Server Integration Services (SSIS) to copy data from a source to a destination via an SSIS Package. Here, the source will be the query to obtain a list of product names and models and we’ll export the results directly to an Excel file destination.

  1. Expand SQL Server in Object Explorer
  2. Right-click on the database you’re exporting from
  3. Tasks
  4. Export Data…

  1. Select Data source: from the dropdown
  2. Confirm or change Server name:
  3. Leave Use Windows Authentication (if you’re using the credentials you’re running SSMS or choose Use SQL Server Authentication and enter login and password)
  4. Confirm or change Database:
  5. Next

  1. Choose a location for destination file
  2. Name file
  3. Open

  1. Choose a version from the Excel version dropdown
  2. Leave the First row has column names checked if your data has headers, uncheck if not
  3. Open

  1. Paste in SQL (take out GOs)
  2. Parse

And here’s your file.

Next Steps

Here are some links to more tips and tutorials on SSMS when exporting SQL Server data to Excel:

Источник

How to Export Data from SQL Server to Excel

Problem

Often there is a need to export data from SQL Server into an Excel spreadsheet. In this tip we look at how this can be done using T-SQL and R to generate an Excel file based on query results.

Solution

The solution that I am proposing is to use sp_execute_external_script to create a simple R script that allows a DBA or Developer, to quickly and automatically export the results of any query to an Excel spreadsheet.

This tip will not explain what is R or how to use sp_execute_external_script procedure. This tip’s goal is to show how to quickly write generic ad-hoc code that will load SQL Server data into an Excel spreadsheet. The advantage is that a DBA or Developer can quickly provide the data to a business user easily and quickly in Excel format.

Download AdventureWorks Database

In this tip, I will use AdventureWorks2014 database that can be easily downloaded and restore it to your SQL Server.

Creation of Excel File from SQL Query using R

The R code that I am using to create the Excel files can be found in my previous article Export SQL Data to Excel. I will use a subset of the code in this example. I will also use Microsoft sp_execute_external_script procedure to invoke R code and pass parameters to it.

R Code

The first part of the scripts focuses with the installation of the necessary packages to work with Excel, in particular, we need to open an Excel package to manipulate our output. The last part of the script, we create the Excel workbook, and save the data. Please note that the Excel file has a static name myTable and the output file is static to D:testmyTable.xlsx.

SQL Query

The T-SQL script can be any script that returns data. The main thing to note is that the @sqlscript variable must be define as NVARCHAR.

Calling sp_execute_external_script

In this step we execute the procedure by passing input to the R and T-SQL code.

Complete Code

Below are all three sets of the above code.

Below is all three sets of code and execution of the code.

The executed script shows our result in SQL Server Management Studio (SSMS) and produced the desired output file. From the file preview we can see that the Excel file contains the data produced by the query in SSMS.

Make Excel File Name Dynamic

To make our script more versatile, we are adding a parameter called @mytname and assign it the file name that we want to create. In the following example, I have assigned the value of «vSalesPerson» to be used to create the output file name and the name of the Excel worksheet.

The below screenshot, highlights the changes to the above script to accommodate the passing of the parameter @mytname.

Here is the code:

When run, we get the file vSalesPerson.xlsx generated instead of a fixed file name like in the first script.

Streamline and Separate R Code

I will remove the R code from the script in order to make it more manageable and readable. The following R code was copied into a text file and saved as «TableToExcel1.r».

As we can see below, all the R code that was present in the previous T-SQL script has been replace by the source() R function that tells the R script to load the code from file D:testTableToExcel1.r.

Here is the code.

Conclusion

We have just demonstrated how easy it is to export SQL Server data to an Excel spreadsheet. Such a script can be handy to a DBA or Developer that needs to provide ad-hoc data to the business in Excel format.

Next Steps

Related Articles

Popular Articles

About the author

Matteo Lorini is a DBA and has been working in IT since 1993. He specializes in SQL Server and also has knowledge of MySQL.

Article Last Updated: 2020-05-22

Comments For This Article

Tuesday, May 31, 2022 — 9:50:12 AM — Matteo Back To Top (90126)
Response to the latest comments:

First of all make sure your R code work outside SQL for example in R Studio
https://www.mssqltips.com/sqlservertip/6396/export-sql-server-tables-to-excel/

Also, it looks like the version of the R openxlsx package is not compatible with the R version installed on your SQL Server.

Tuesday, May 31, 2022 — 8:09:02 AM — OSMAN Back To Top (90125)
Hi, ı like the content and try to do that. But some errors were thrown. In MS SQL ı try to export a table using R scripts.I RUN THE SİMPLE ARITHMETICAL PROCESS AND GOT THE SOLUTİON. But otherwise ıf we use R services’ library, codes throw runtime error. Is the any one to help me. Thanks
Tuesday, January 5, 2021 — 11:38:03 AM — Matteo Lorini Back To Top (88004)
Ali,
it looks like the account that runs SQL Server does not have permission to write to that drive. This is a Account/Permission issue. Try to write to another folder or add permissions to the E: drive for the account that runs the SQL Server service.
Monday, January 4, 2021 — 8:33:43 PM — Ali Back To Top (87997)
Hello Mr. Lorini 🙂

I did all the requirements and still face one fatal problem. The R script tries to create the excel file but is denied the write permission on the local drive. The error returned is the following from the messages section of SSMS:

Warning message:
In file.create(to[okay]) :
cannot create file ‘e: 1399.10.16.xlsx’, reason ‘Permission denied’

I truly appreciate your help. 🙂
Thanks,
Ali

Wednesday, December 30, 2020 — 11:57:30 AM — Matteo Lorini Back To Top (87981)
Ali, make sure that R
MSSQL R Serviceis installe see: https://www.mssqltips.com/sqlservertip/6465/quick-start-guide-for-data-science-with-sql-server-and-r-services/

Also make sure that this is enable:

EXEC sp_configure ‘external scripts enabled’, 1
RECONFIGURE WITH OVERRIDE

Tuesday, December 29, 2020 — 3:26:25 AM — Ali Back To Top (87963)
Hi Mr. Lorini

I get 2 errors in this solution. when I run SQL script under ssms i get the following error:

Msg 39020, Level 16, State 2, Procedure sp_execute_external_script, Line 1 [Batch Start Line 0]
Feature ‘Advanced Analytics Extensions’ is not installed. Please consult Books Online for more information on this feature.

when I run r script the following error is returned:

Error in saveWorkbook(wb, file = paste(«D:\test\myTable», «.xlsx», sep = «»), :
could not find function «saveWorkbook»

I appreciate your help 🙂
Thanks,
Ali

Thursday, November 19, 2020 — 11:15:29 PM — Mithalesh Gupta Back To Top (87814)
Thanks a lot for this informative post.
You are one of very few bloggers who has explained approach in a step-wise manner.

Thanks you

Excellent article — this is exactly what I need to do! Thanks for the clear and consise explanation 🙂

Источник

Adblock
detector

Friday, May 22, 2020 — 9:11:36 AM — Ginger Back To Top (85725)

The export function for query result is not so obvious for developers to find out. In this post, I will show how to export query result as a Excel file.

Show Query Result as Grid

To show the query result in a grid table, you have to use F9 or Ctrl+Enter to format query result in grid.

SQL Developer Query Result

SQL Developer Query Result

Right Click Mouse and Export

Move your cursor over anywhere on the grid and right click the mouse, you will see Export option.

SQL Developer Query Result - Export

SQL Developer Query Result — Export

Export Entire Table

If the data you want to export is a table, not a query result, you can directly right-click on the table and select Export in the menu.

SQL Developer - Table Menu - Export

SQL Developer — Table Menu — Export

Select Export Format

SQL Developer showed Export Wizard window for interaction. Although there’re many export types for us to select, we chose Excel format in this case.

SQL Developer Query Result - Export Format - Excel (.xls)

SQL Developer Query Result — Export Format — Excel (.xls)

Select Text Encoding

I chose UTF-8 in order to match the database encoding.

SQL Developer Query Result - Export Encoding - UTF-8

SQL Developer Query Result — Export Encoding — UTF-8

Customize Filename

If you want to change the path, you can click Browse to navigate and choose a right directory to place.

SQL Developer Query Result - Export File Name - Browse

SQL Developer Query Result — Export File Name — Browse

Review Export Job Before Executing

You can expand all options to see the content of the export job.

SQL Developer Query Result - Export - Summary

SQL Developer Query Result — Export — Summary

Check Content of Excel File

We open the Excel file in an application, so they can be viewed its content below.

SQL Developer Query Result - Export - Excel File Content

SQL Developer Query Result — Export — Excel File Content

That’s it!

Next, we can restore the Excel data back into table by importing data in SQL Developer whenever needed.

Do you find it difficult to export your data from Oracle SQL Developer to excel and CSV format? Have you ever just banged your hands at the keyboard, closed your eyes, and thought “Is it supposed to be this hard?”. Well, the answer is NO. This post will guide you step by step with necessary screenshots through the whole process of Oracle SQL Developer export to excel & CSV format.

It’s every developer’s dream to be able to manipulate and convert their data into any format. Often this takes a lot of effort and resources just to get the already painstakingly gathered data to the desired format. One such example is exporting your data from Oracle SQL Developer to excel and CSV format. 

Introduction To Oracle SQL Developer

Oracle offered a database IDE in the form of Oracle SQL Developer. It supports the graphical user interface i.e. any user or administrator can perform the database activities in fewer clicks. It simplifies Oracle database development and management on a traditional and cloud-based platform. They also provide export and import utilities to their users. You can explore more about the functionalities of Oracle here.

Oracle’s main objective is to save the user’s time and effort in every possible way. So, the process of Oracle SQL Developer export to excel and CSV format should be a painless and ephemeral task. Let’s see how you will conquer this feature of Oracle.

Oracle SQL Developer Export to Excel: Oracle SQL

Image Source: www.logo.wine/logo

Hevo offers a faster way to move data from databases such as Oracle; SaaS applications and 100+ other data sources into your data warehouse to be visualized in a BI tool. Hevo is fully automated and hence does not require you to code.

Get Started with Hevo for Free

Let’s look at the benefits of using Hevo:

  • Secure Data Transfer: Hevo offers two-factor authentication and end to end encryption, which makes sure that the data movement is safe and secure.
  • Fully-Automated: Hevo platform requires minimal maintenance and management. This fully automated service is a wise choice for anyone.
  • Auto Mapping: It can automatically create the schema by mapping the data from the source to the destination schema. Hevo takes care of the mapping even when there are changes in the latter stage.
  • Scalability: Hevo can handle millions of records per minute without any latency. The data pipelines are scaled according to the requirement.
  • Friendly Live Support: Hevo team is ready to offer a helping hand at any time through emails, chat, and calls. 

Sign up here for a 14-Day Free Trial!

Download the Ultimate Guide on Database Replication

Download the Ultimate Guide on Database Replication

Download the Ultimate Guide on Database Replication

Learn the 3 ways to replicate databases & which one you should prefer.

Let’s see what you will cover here:

  • Prerequisites
  • Steps For The Exporting Process

Prerequisites

  • Oracle SQL Developer installed on your system.
  • Knowledge about RDBMS.

Steps For The Exporting Process

The steps involved in creating an excel and CSV file from the data in Oracle SQL Developer are listed below:

  1. Connect Your Database
  2. Run Your Query
  3. Export Your Data
  4. Select Your Desired Format
  5. Use Your Data In The Desired Format

Step 1: Connect Your Database

Connect to your database in Oracle SQL Developer by using the correct credentials of your database. This database contains the data that needs to be exported to an Excel or CSV file.

Oracle SQL Developer home

Image Source: www.docs.oracle.com/en/cloud

Step 2: Run Your Query

Write the following command in the SQL worksheet and execute it by clicking the run button on the top left corner of the worksheet. You can also use any other query to get your desired output.

SELECT * FROM ACCOUNTS;

Run Query

Image Source: www.youtube.com

Step 3: Export Your Data

Right-click on the query result and select Export from the drop-down menu.

Oracle SQL Developer Export

Image Source: www.stackoverflow.com/questions

Step 4: Select Your Desired Format

In the Export Wizard, select “excel 2003+ (xlsx)” for excel versions above 2003 or “excel 95-2003 (xls)” for excel version between 95 and 2003 or “csv” in the format, and then determine your destination location. Click “Next” and then “Finish”.

Oracle SQL Export Wizard

Image Source: www.docs.oracle.com/cd

Step 5: Use Your Data In The Desired Format

Finally, you can go to your destination location and open the exported data in the specified format.

Conclusion

You have learned the process of Oracle SQL Developer export to excel and CSV format. The data that you have exported is usually needed for backup or to transfer that data to another database or a data warehouse. Extracting complex data from a diverse set of data sources can be a challenging task and this is where Hevo saves the day!

Visit our Website to Explore Hevo

Hevo, a No-code Data Pipeline helps you transfer data from Oracle SQL Developer in a fully automated and secure manner without having to write the code repeatedly. Hevo, with its secure integrations with 100+ sources & BI tools, allows you to export, load, transform, & enrich your data & make it analysis-ready in a jiffy.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable pricing that will help you choose the right plan for your business needs.

Let us know about your experience of Oracle SQL Developer export to Excel and CSV in the comment section below. 

No-code Data Pipeline for Oracle

In several scenarios, we need to use some data which is available in SQL Server, but we need it in MS Excel. Instead of putting every data manually into Excel, the SQL Server provides an option to import and export data from SQL Server to Excel sheets. In this tutorial, we will learn various methods of importing and exporting data from or to SQL Server. Also, we will cover these topics.

  • How to export data from SQL Server to Excel using Import and Export Wizard
  • How to export data from SQL Server to Excel automatically
  • How to export data from SQL Server to Excel using the query
  • How to import data from SQL Server into Excel using Data Connection Wizard
  • Export data from SQL Server to Excel using stored procedures

Here, for all the functionality, I have used SQL Server 2019 Express edition.

Export data from SQL Server to Excel using Import and Export Wizard

In this section, we will learn how to export data from the SQL Server database into an Excel worksheet automatically using import & export Wizard. We will be using the import and export wizard in SQL Server Management Studio.

  • Below is the table that we are going to export automatically using the import and export wizard in SQL Server.
export data from SQL Server to Excel using Import and Export Wizard
Data to be Imported
  • Right-click on the database using which table is created.
  • Select the Tasks option from the dropdown another dropdown will appear.
  • Click on the Export Data.
Import to Excel Wizard in sql server
Running the Import and Export Wizard
  • Once you have clicked on the Export Data option from the drop-down menu then Import and Export wizard window will appear.
  • Click on Next to proceed in the process.
Export data from SQL Server to Excel
Import and Export Wizard
  • Once you have clicked on the Next button on Import and Export wizard a new window will appear asking to Choose a Data Source
  • Select SQL Server Native Client 11.0 in Data Source
  • Select the instance from the dropdown for the Server name.
  • For Authentication, you can use:
    • Use Windows Authentication, which means the username and password of your computer. It automatically picks up from the system.
    • Use SQL Server Authentication, this requests the Username and Password that was creating an instance.
  • Select the database name from the dropdown and click on the Next button.
export data from SQL Server to Excel using Import and Export Wizard
Data Source
  • The SQL Server Import and Export Wizard will ask for destination details. Choose Destination field as Microsoft Excel
  • Give the path to the Excel file into which you want to export the data
  • Select the Excel Version according to the version of the Excel that you have installed on your system and click Next.
How to export data from SQL Server to Excel using Import and Export Wizard
Data Destination
  • Now the SQL Server Import and Export Wizard will ask whether you want to copy all data from the existing tables or query-specific data. We can select Copy data from one or more tables or views to import all the table data.
  • We will also explain how you can copy data that is modified by SQL query with Write a query to specify the data to transfer option

Read: How to Create a Database in SQL Server 2019 [Step by Step]

Export data from SQL Server to Excel automatically

SQL Server 2019 provides a method to export all the data from SQL server to Excel worksheet. In this section, we will demonstrate how to export SQL server data to Excel automatically using Import and Export Wizard.

Import to SQL specify table copy
Specify type of Operation
  • Choose the table from the Source tab which you want to export and specify the name of the table in the Destination tab and click Next
How to export data from SQL Server to Excel
Select Table
  • In the next step, you can choose whether you want to save the SSIS Package or not. In this section, we will continue without saving.
How to export data from SQL Server 2019 to Excel
Run Package
  • Now you will see the final overview of the operation before the execution, click on the Finish Button.
How to export data from SQL Server to Excel automatically
Final Overview
  • Now data has been successfully exported from SQL Server to Excel worksheet.Click on the Close button to exit the window.
How to export data from SQL Server to Excel
Process Completed
  • You can check that the file is created at the specified location.
How to export data from SQL Server to Excel automatically
Exported Data Successfully

Read: How to create a table in sql server management studio

At times, it is not necessary to export all the table data. Instead, we need to export data using a query. In such situations, we can export query-specific data from SQL Server to Excel worksheet.

  • After selecting the source and destination of data using SQL Import and Export Wizard, the wizard show two options. Choose the second option which says Write a query to specify the data to transfer and then click on the Next button.
export data from SQL Server to Excel using query
Export Using Query
  • Then we need to specify the query which we want to implement. In our case we will execute a query to show the Name and Age of people whose salaries are greater than 100000. After writing the query, click Next
export data from SQL Server 2019 to Excel using query
Writing the Query
  • Now you will see the overview of table source and destination. You can also see how the data looks after the query is implemented by clicking on the Preview button. Then click Next
export data from SQL Server 2017 to Excel using query
Data Preview
  • Run immediately is checked by default, click on Next button.
How to export data from SQL Server to Excel using query
Save and Run Package Windows
  • Now all the configurations are complete. You can click on the Finish button to start the Wizard
How to export data from SQL Server to Excel using query
Complete the Wizard
  • If all actions are successfully completed, your query is implemented and the data is exported. You can close this window.
Import from SQL to Excel Execution success
Success
  • Navigate to the destination path and you can see that data is exported successfully
How to export data from SQL Server to Excel using query
Exported Data

Read: Advanced Stored Procedure Examples in SQL Server

How to import data from SQL Server into Excel using Data Connection Wizard

We can also import data from SQL Server to Excel using the Data Connection Wizard in Excel. The benefit of using this method is that we can get live data from SQL Server.

Live data means that the changes made in the SQL Server database will be reflected into the Excel worksheet also. We will demonstrate this with the help of an example

  • Open MS Excel and create a new worksheet or open an existing worksheet into which you want to import the data from SQL Server
  • Go to the Data tab and click on From Other Sources and then From SQL Server as shown in the image below
import data from SQL Server into Excel
Create Connection to SQL Server
  • Enter the name of the Server instance that you have created in the Server name field. You can use either Windows Authentication or SQL Server login credentials to make a connection with the database. After inserting the required details, click Next
import data from SQL Server 2019 into Excel
Data Connection Wizard
  • Now select the database and the table that you want to import. You can also import data from multiple tables by checking the option Enable selection of multiple tables
How to import data from SQL Server into Excel
Select Database and Table
  • Save the Data Connection File. Add description to it to store more information about the connection. It will help you to know the information about the connection when you will connect to the database again. Click Next
How to import data from SQL Server 2019 into Excel
Save Connection
  • A small window will appear where you can decide how you want to view your data in the Excel Workbook. You can import the data either in an existing worksheet or in a new worksheet. Select the desired option and then click OK
How to import data from SQL Server 2017 into Excel
Format Data
  • Now you can see, your data is imported successfully from SQL Server
How to import data from SQL Server into Excel
Imported Data
  • As mentioned above, this type of connection is a live connection to the database. Try to change the data in SQL Server. You will see that the changes will be reflected in the Excel worksheet also. Let us see an example
  • Run the following query in the SQL Query Window in SQL Studio Management
update Employees set Age =20 where [Employee ID]=1;
select * from Employees;

Here is the implementation of above mentioned code snippet.

import to excel updated data studio
Result after Query
  • Changes are made in the table. Now refresh the excel worksheet where you have imported the data or open it again. You will the same changes in the imported data
how to import data from SQL Server into MS Excel
Updated Data

In this tutorial, we have learned how to import data from SQL Server into MS Excel using Import and Export wizard in different ways. Also, we have covered these topics.

Export data from SQL Server to Excel using stored procedures

  • There is a method in SQL Server called OPENROWSET method which is used to export data from SQL Server to Excel
  • OPENROWSET method has some requirements that need to be fulfilled before we can use this method
    • Administrator permissions to SQL Server Management Studio
    • enable “Show Advanced Options”
    • enable “Ad Hoc Distributed Queries”
  • Run SQL Server Management Studio as Administrator
  • Write the query following query to enable these options
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries',1;
RECONFIGURE;
GO
Export data from SQL Server to Excel
Configuring sp_configure
  • Give permissions to the Microsoft.ACE.OLEDB.12.0 driver by excecuting the following command
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
  • After successfully running the above commands, you have to create an Excel sheet with the same fields which are there in the database table
Export data from SQL Server 2019 to Excel
Field Names
  • Now you can write the query to export data from SQL Server to Excel
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersBladesDesktopexported_data.xls;','SELECT * FROM [Sheet1$]')
Select * from Employees;
  • Remember to set the Database path, Excel file name, Excel worksheet name and database name in the above query
  • You may encounter the following error while executing the query
  • This error states that the SQL Server is running on 64-bit architecture but Microsoft Access Database Engine only has 32-bit drivers installed

How to Export data from SQL Server to Excel

Version Error

This means you have to download the 64-bit Access Database Engine

You can download the 64-bit version of Access Database Engine from the specified link

Install Access Database Engine and this will install the 64-bit version of Microsoft.ACE.OLEDB.12.0 driver.

Now run the query again

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersBladesDesktopexported_data.xls;','SELECT * FROM [Sheet1$]')
Select * from Employees;
  • Now you can see, the query is run successfully
Export data from SQL Server 2019 to Excel using stored procedures
Success Message
  • You can open the Excel file and see if the data is exported
Export data from SQL Server to Excel using stored procedures
Exported Data
  • You can use this OPENROWSET method in your own stored procedure and export data from SQL Server to Excel.

You may like the following sql server articles:

  • SQL Server Substring Function
  • SQL Server Replace Function + Examples
  • SQL Server Convert String to Date

In this tutorial, we learned about the various methods of exporting the data from SQL Server to Excel. We solved some encountered errors also.

  • How to export data from SQL Server to Excel using Import and Export Wizard
  • How to export data from SQL Server to Excel automatically
  • How to export data from SQL Server to Excel using the query
  • How to import data from SQL Server into Excel using Data Connection Wizard
  • Export data from SQL Server to Excel using stored procedures

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.

Like this post? Please share to your friends:
  • Export pdf with word
  • Expression error ключу не соответствует ни одна строка в таблице excel
  • Export one sheet from excel
  • Expression error аргументы 2 были переданы функции которая ожидает 1 excel
  • Export java to excel