0

I am new to Stack overflow as well as Python. Below is my program and I am trying to learn how to export data from SQL server to excel using python program. I know ways to directly exporting from SQL server, this is I am just trying to learn. Program below does not give any errors but it does just gives column headers but not actual data.

import pyodbc
import pandas as pd

cnxn = pyodbc.connect("Driver={SQL Server};SERVER=hostname;Database=Practice;UID=XXX;PWD=XXX")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM insurance')

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

writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, sheet_name='bar')
writer.save()
2
  • dude, maybe is on purpose but just in case, you have username and password there!!! Commented Jan 15, 2018 at 16:37
  • Thanks for pointing out. But i changed before posting. Commented Jan 16, 2018 at 16:44

1 Answer 1

10

easier than that!

import pyodbc
import pandas as pd

cnxn = pyodbc.connect("Driver={SQL Server};SERVER=xxx;Database=xxx;UID=xxx;PWD=xxx")

pd.read_sql('SELECT * FROM insurance',cnxn).to_excel('foo.xlsx')
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome it worked pretty well. Can you please help me understand why did not work with my code?
Error i was getting was ValueError: Shape of passed values is (1, 64), indices imply (153, 64)
Ths answer solved me from an headache. There is just one typo: data = pandas.read_sql('SELECT * FROM insurance',cnxn) Should read data = pd.read_sql('SELECT * FROM insurance',cnxn)

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.