我最近刚接触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
我的主要问题是:
提前致谢,请编辑或评论或询问更多详情。
欢迎所有答案!
感谢stovfl的评论,我能够确定该目录不存在,所以我只是将其更新为新值。这解决了问题,但现在出现了另一个问题:当我尝试在工作簿中写入时,它说我的每一行都有错误,如下所示:
Error in line 61418
data=('04/05/2017', 'xxxx', 'xxxxx', 'xxxxx', 100.0, 99.03, 99.15, 4.73)
新问题是,为什么我无法写入Excel工作簿。
答案 0 :(得分:0)
修改以下内容,将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
答案 1 :(得分:0)
经过一些测试和解决方法后,我找到了解决问题的方法。
SELECT PARSE_TIMESTAMP('%Y%m%d', CAST(SQLDATE AS STRING)) AS SQLDATE_PARSED,
FROM blockchain_data AS blockchain
INNER JOIN GDELT
-- not what you want, but what you do, with error TIMESTAMP = INT64
ON blockchain.timestamp = SQLDATE
-- what you want, but show ERROR column not fould
ON blockchain.timestamp = SQLDATE_PARSED
-- Is the valid expression
ON blockchain.timestamp = PARSE_TIMESTAMP('%Y%m%d', CAST(SQLDATE AS STRING))