0

How to export sql database to excel including column name also (using python)? Here I tried it:

import pyodbc
import pandas as pd

cnxn = pyodbc.connect("myconnection")
cursor = cnxn.cursor()
a=input("enter your source code:")
script = """
xlsexcel '"+a+"' """
cursor.execute(script)
b=list()
for row in cursor:
   b.append(row)
   print(b)
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame(list(data), columns=columns)
df = pd.read_sql_query(script, cnxn)
writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, sheet_name='bar')
writer.save()
1
  • 3
    where did it not work? Commented Jul 2, 2019 at 5:43

1 Answer 1

1

Pandas reads data directly from your database connection:

import pyodbc
import pandas as pd


sql_query = input("enter sql query:")

with pyodbc.connect("myconnection") as c:

    df = pd.read_sql(sql_query, c)

    with pd.ExcelWriter('foo.xlsx') as writer:
        df.to_excel(writer, sheet_name='bar')

This ought work

Sign up to request clarification or add additional context in comments.

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.