【问题标题】:how to write the results of a stored procedure into an excel file with python如何使用python将存储过程的结果写入excel文件
【发布时间】:2017-04-06 07:04:46
【问题描述】:

我最近刚接触 Python,我正在编写一段代码,该代码可以连接到我的一个数据库以获取所有行和列,因此我可以将这些数据保存到一个列表中,然后编写将其保存到 Excel 文件中。这是我写的一段代码:

#create the MSSQL connection with python
table_one_connection = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="you-cant-see-me", pwd="guessme",Trusted_Connection = "No")

table_one_connection_results = []
row_table_one = 0

#set the cursor for table_one
cursor = table_one_connection.cursor()
cursor.execute("[data].[Tableschema].[DEFINED_SP] @start_date='xx-xx-xx', @end_date='xx-xx-xx'")

#get all the rows from the SP
results = cursor.fetchall()

#append the results into a list 
for index, result in enumerate(results):
    table_one_connection_results.append(result)

#start writing the results into an Excel file
results_workbook = xlwt.Workbook()
results_sheet    = results_workbook.add_sheet("SP values")

#insert the list results into the Excel file 
for index, value in enumerate(table_one_connection_results):
    results_sheet.write(row_table_one,0,value)
    row_table_one = row_table_one + 1

#write the workbook
results_workbook.save("C:\\Users\\UserX\\Desktop\\E\\output\\export_results.xls")

现在,问题来了,当代码试图将数据写入 Excel 文件时,计算机显示以下错误:

Traceback (most recent call last): 
    line 284 in __rich_text_helper
    raise Exception ("Unexpected data type %r" % type(data))
    Exception: Unexpected data type <class 'float'>

现在,我担心我在第 1 列(Excel 中的 A 列)中写入数据,并且我尝试迭代每个列表项以将它们写入单独的行中,但是,我相信这不是我想要的正确解决方案但相反,我希望看到每个列表项分隔在不同的列和不同的行中,如下所示:

column A   column B   column C

value_one  value_two  value_three

而不是

column A
value_one,    value_two,    value_three
new_value_one new_value_two new_value_three

我的主要问题是:

  1. 为什么我会收到此意外数据类型的异常错误
  2. 我希望将每个列表项分成不同的列和不同的行。我怎样才能做到这一点?奖励:有没有更好的方法来实现这个目标而不使用列表?字典呢?这可能吗?

提前致谢,请编辑或评论或询问更多详情。

欢迎所有答案!

更新

感谢 stovfl 的评论,我能够确定该目录不存在,所以我只是将其更新为新值。这解决了第一个问题,但现在出现了另一个问题:当我尝试在工作簿中写入时,它说我每一行都有错误,如下所示:

Error in line 61418
data=('04/05/2017', 'xxxx', 'xxxxx', 'xxxxx', 100.0, 99.03, 99.15, 4.73)

新问题是,为什么我不能写入 Excel 工作簿。

【问题讨论】:

  • 只是猜测。在您的for index, value in ... 中,value 看起来像是一个元组(或其他一些集合)。您可能无法直接将元组写入 Excel。如果您一次从集合中写入一个值怎么办?
  • 我怎样才能做到这一点?我现在正在检查这个结果,我正在考虑将查询结果存储到其他数据结构中,以便我可以轻松枚举并将其写入 Excel 文件。
  • 在你的for 循环中,你会首先用v0, v1, ..., vn = value 之类的东西解压元组。 (将 v0...vn 替换为更有意义的名称)。然后用results_sheet.write(row_table_one, 8, v4)之类的东西将每一个写入Excel,将v4放在电子表格的第8列。

标签: python sql-server excel pycharm


【解决方案1】:

经过一些测试和解决方法,我找到了解决问题的方法。

#create the MSSQL connection with python
table_one_connection = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="you-cant-see-me", pwd="guessme",Trusted_Connection = "No")

#set the cursor for table_one
cursor = table_one_connection.cursor()
cursor.execute("[data].[Tableschema].[DEFINED_SP] @start_date='xx-xx-xx', @end_date='xx-xx-xx'")

#Fetching data
cursor.fetchall()

#Create the workbook of results
print("Generating the workbooks with the database data")
cursor_results_workbook   = xlwt.Workbook()
results_sheet             = cursor_results_workbook.add_sheet("SP values")

#row counter that you use to move from rows
row_counter = 0

#write the data onto the Excel file
for index,value in enumerate(cursor):
    try:
        #extract from the tuple 'results' the value of each item and store it in every column for all rows
        results_sheet.write(row_counter, 0, value[0])
        results_sheet.write(row_counter, 1, value[1])
        results_sheet.write(row_counter, 2, value[2])
        results_sheet.write(row_counter, 3, value[3])
        results_sheet.write(row_counter, 4, value[4])
    except:
        print("Error in line %s\n data=%s" % (index, value))
    row_counter = row_counter + 1

cursor.close()

【讨论】:

    【解决方案2】:

    编辑以下内容以将row string 拆分为column values

    for index, value in enumerate(table_one_connection_results):
        results_sheet.write(row_table_one,0,value)  
    

    for index, value in enumerate(table_one_connection_results):
        for col, col_value in enumerate(value.split(',')):
            try:
                results_sheet.write(row_table_one, col, col_value)
            except:
                print('Error in line %s, column %s\ndata=%s' % (index, col, table_one_connection_results[index]) )  
    

    使用的文档:xlwt API Reference

    【讨论】:

    • 你好@stovfl,你的建议奏效了,现在我能够检测到发生异常错误的原因,但现在当循环尝试写入 Excel 文件时,我发现所有行都有错误。还有其他建议吗?
    • @AlejandroRamos:更新了我的答案
    猜你喜欢
    • 2018-04-07
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多