简体   繁体   English

使用Python从SQL数据库到Excel

[英]From SQL Database to Excel with Python

I am new to Python. 我是Python的新手。 I've successfully connected to my SQL database via an odbc connection and I am pulling data from a table. 我已经通过odbc连接成功连接到SQL数据库,并且正在从表中提取数据。 How do I then get that data into a Excel workbook. 然后如何将这些数据放入Excel工作簿中。 Preferably using the xlsxwriter module. 最好使用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 is the easiest bet for this. pandas是最简单的选择。 Here's an example using sqlite as the database backend: 这是一个使用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")

Lines 41 and 43 are the main ones, and this results in a single sheet Excel doc named out.xlsx in the current folder. 第41和43行是主要行,这将在当前文件夹中生成一个名为out.xlsx表Excel文档。

Since you already have your data, it seems like your question is simply how to get your data into Excel. 由于您已经有了数据,因此您的问题似乎只是如何将数据导入Excel。 Let's say you have data in an object named rows , which is a list of result rows. 假设您有一个名为rows的对象中的数据,该对象是结果行的列表。

import xlsxwriter
workbook = xlsxwriter.Workbook('YourResults.xlsx')
worksheet = workbook.add_worksheet()

row = 0
col = 0

for row_data in rows:
  worksheet.write(row, col, row_data.1)
  worksheet.write(row, col+1, row_data.2)
  worksheet.write(row, col+2, row_data.3)
  row += 1

workbook.close()

This should write rows of data to your spreadsheet. 这会将数据行写入电子表格。 You can view the xlsxwriter tutorial here: https://xlsxwriter.readthedocs.io/tutorial01.html 您可以在此处查看xlsxwriter教程: https ://xlsxwriter.readthedocs.io/tutorial01.html

Just as an aside, you can also access SQL and Excel via ADO (using COM), however, if you're just beginning with Python, that might be a bit more challenging. 顺便说一句,您还可以通过ADO(使用COM)通过ADO访问SQL和Excel,但是,如果您刚开始使用Python,则可能会更具挑战性。 If you're interested in looking at that later, here's a primer on ADO in python: http://mayukhbose.com/python/ado/index.php 如果您有兴趣以后再看,这里是python中的ADO入门: http : //mayukhbose.com/python/ado/index.php

If the Pandas package is available to you, you can easily dump a DataFrame to an Excel spreadsheet. 如果您可以使用Pandas软件包,则可以轻松地将DataFrame转储到Excel电子表格中。 Formatting is also accessible. 也可以访问格式。 You'll need to get the data into a DataFrame by appending rows to a list (not sure how pyodbc works). 您需要通过将行追加到列表中来将数据获取到DataFrame中(不确定pyodbc的工作方式)。 Something like: 就像是:

import pandas as pd

data = []
...
for rows in cursor:
    for row in rows:
        data.append(row)

df = pd.DataFrame(data)

Then dump to Excel. 然后转储到Excel。

def df_to_excel(path,data_frame):
    writer = pd.ExcelWriter(path, engine='xlsxwriter')
    data_frame.to_excel(writer, index=False, sheet_name='SHEET0')    # sheet 0
    writer.save()
import xlsxwriter

workbook = xlsxwriter.Workbook('your_excel.xlsx')
worksheet = workbook.add_worksheet()

The first version writes one value (ie row ) in each column sequentially. 第一个版本在每个列中顺序写入一个值(即row )。

for index, row in enumerate(cursor):
    worksheet.write(0, index, row)
workbook.close()

The second version writes one value (ie row ) in each row sequentially. 第二种版本在每一行中顺序写入一个值(即row )。

for index, row in enumerate(cursor):
   worksheet.write(index, 0, row)
workbook.close()

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

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