简体   繁体   中英

how to export sql database to excel using python

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM