xlsxwriter错误-尝试将SQL输出写入Excel工作表

时间:2018-09-19 08:55:12

标签: python xlsxwriter

我正在尝试使用XLSXwriter模块将SQL查询的输出写入Excel。

dwh_cur.execute("""select count (*) from sales where created_at = current_date - 1""")
sales = dwh_cur.fetchall()
worksheet1.write('A1', 'Sale ID')

row = 1
col = 0

for elm1 in sales:
    worksheet1.write(row, col, elm1)
    row += 1

遇到错误:

TypeError: float() argument must be a string or a number, not 'tuple'

以下是我要写入excel文件的数据

Sale_ID
1001
1002
1003
1004
1005

任何人都可以协助我解决问题。谢谢。

1 个答案:

答案 0 :(得分:3)

dwh_cur.fetchall()返回一个元组列表,可能是:

[(1001,), (1002,)]

考虑到这一点,您应该将单元格编写如下:

dwh_cur.execute("""select count (*) from sales where created_at = current_date - 1""")
sales = dwh_cur.fetchall()
worksheet1.write('A1', 'Sale ID')

row = 1
col = 0

for elm1 in sales:
    worksheet1.write(row, col, elm1[0])
    row += 1

您还可以使用Python的enumerate()函数自动为您提供行号:

dwh_cur.execute("""select count (*) from sales where created_at = current_date - 1""")
sales = dwh_cur.fetchall()
worksheet1.write('A1', 'Sale ID')

col = 0

for row, elm1 in enumerate(sales, start=1):
    worksheet1.write(row, col, elm1[0])

如果要返回多个项目,即第二列,则可以按如下所示添加它们:

for row, elm1 in enumerate(sales, start=1):
    worksheet1.write(row, col, elm1[0])
    worksheet1.write(row, col+1, elm1[1])