简体   繁体   English

使用python pyodbc和pandas数据框将数据从SQL服务器导出到Excel

[英]Exporting data from SQL server to Excel using python pyodbc and pandas Data frame

I am new to Stack overflow as well as Python.我是堆栈溢出和 Python 的新手。 Below is my program and I am trying to learn how to export data from SQL server to excel using python program.下面是我的程序,我正在尝试学习如何使用 python 程序将数据从 SQL 服务器导出到 excel。 I know ways to directly exporting from SQL server, this is I am just trying to learn.我知道直接从 SQL 服务器导出的方法,这是我只是想学习。 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()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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