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?
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With