Skip to main content
 首页 » 编程设计

python之使用 Python 从 SQL 数据库到 Excel

2025年05月04日24shanyou

我是 Python 新手。我已经通过 odbc 连接成功连接到我的 SQL 数据库,并且我正在从表中提取数据。然后如何将该数据导入 Excel 工作簿。最好使用 xlsxwriter 模块。

import pyodbc 
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSERVER;PORT=XX;DATABASE=dbname;UID=sa;PWD=##') 
cursor = cnxn.cursor() 
cursor.execute("select * from T1 where C2 not like '%text%'") 
for row in cursor: 
        print row.1, row.2, row3 
 
cursor.close() 
cnxn.close() 

请您参考如下方法:

pandas 是最简单的选择。下面是一个使用 sqlite 作为数据库后端的例子:

In [38]: import pandas as pd 
 
In [39]: df 
Out[39]: 
          0         1         2         3         4 
0  0.092719  0.664147  0.677834  0.605845  0.569223 
1  0.656272  0.321661  0.294219  0.818676  0.010610 
2  0.041692  0.721683  0.163525  0.175113  0.580234 
3  0.852775  0.106076  0.049080  0.649362  0.265763 
4  0.481842  0.942276  0.462951  0.386705  0.205302 
 
In [40]: df.to_sql("tbl", sqlite3.connect("test.sqlite"), index=False) 
 
In [41]: new_df = pd.read_sql("select * from tbl", sqlite3.connect("test.sqlite")) 
 
In [42]: new_df 
Out[42]: 
          0         1         2         3         4 
0  0.092719  0.664147  0.677834  0.605845  0.569223 
1  0.656272  0.321661  0.294219  0.818676  0.010610 
2  0.041692  0.721683  0.163525  0.175113  0.580234 
3  0.852775  0.106076  0.049080  0.649362  0.265763 
4  0.481842  0.942276  0.462951  0.386705  0.205302 
 
In [43]: new_df.to_excel("out.xlsx") 

第 41 行和第 43 行是主要内容,这会在当前文件夹中生成一个名为 out.xlsx 的单张 Excel 文档。