如何使用python将sql数据库导出到excel

时间:2019-07-02 05:42:47

标签: python

如何将包括列名在内的sql数据库导出到excel(使用python)?我在这里尝试过:

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 个答案:

答案 0 :(得分:1)

Pandas直接从数据库连接读取数据:

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

这应该可行