5

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?

2
  • Do you have something working? Querying the DB? or exporting to excel? Commented Sep 24, 2013 at 9:18
  • i have sql quary result. i need that quary export to excel using python code.. i dont have any python code yet Commented Sep 24, 2013 at 9:22

4 Answers 4

19

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to use this script and had errors, so after posting to this thread: stackoverflow.com/questions/31550031/… the solution was to change df = pd.read_sql_query(script, cnxn) and that worked...
Thanks for the tip! I don't remember what version of pandas I was using at the time but it's definitely old which may be why it didn't work.
needed to run also pip install openpyxl. thank you!
2
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")

1 Comment

You can simply get the query result in pandas dataframe and get into a Excel file.
0

Take a look at the following modules:

  • pyodbc - connecting to SQL Server
  • xlwt - writing to an Excel spreadsheet

If you're still having issues after installing those modules and reading through the documentation, then you are welcome to request further assistance by posting your script in a new question, along with any error messages seen. :)

Comments

0

I've had great success with openpyxl before and their tutorial is simple but comprehensive enough to get going without tripping over what gotchas there are.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.