Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Export Sql Server Result to Excel in Python

Tags:

python

I'm working with our own framework

I want to export sql server result set (queried one) to excel using ion python.

Inside the python file I can call that sql query result.

Then I want to export that query result in to excel with headers.

That means that once I call the python file, that query result should be saved as an excel spreadsheet.

Please any one can help me to make this correctly?

like image 824
user2768851 Avatar asked Dec 05 '22 09:12

user2768851


2 Answers

I would do this with pyodbc(for interacting with the db) and pandas (for manipulating data and exporting as spreadsheet).

Here's a simple example:

import pyodbc
import pandas as pd

cnxn = pyodbc.connect(< db details here >)
cursor = cnxn.cursor()
script = """
SELECT * FROM my_table
"""

cursor.execute(script)

columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame(list(data), columns=columns)

writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, sheet_name='bar')
writer.save()

Read through the docs and you'll be fine.

== UPDATE ==

For more recent versions of pandas this is a better way to process the SQL query:

import pyodbc
import pandas as pd

cnxn = pyodbc.connect(< db details here >)
script = """
SELECT * FROM my_table
"""

df = pd.read_sql_query(script, cnxn)
like image 112
moarCoffee Avatar answered Dec 16 '22 03:12

moarCoffee


import pandas as pd
import xlsxwriter
import pyodbc


conn = pyodbc.connect('Driver={SQL Server}; Server=ServerIP; uid=UID; pwd=Password; Trusted_Connection=No;')
 with pd.ExcelWriter("Output.xlsx", engine="xlsxwriter", options = {'strings_to_numbers': True, 'strings_to_formulas': False}) as writer:
        try:
            df = pd.read_sql("Select * from Orders", conn)
            df.to_excel(writer, sheet_name = "Sheet1", header = True, index = False)
            print("File saved successfully!")
        except:
            print("There is an error")
like image 41
Manish Chaudhary Avatar answered Dec 16 '22 05:12

Manish Chaudhary