【问题标题】:Error writing data from Dataframe to excel sheet using xlsxwriter使用 xlsxwriter 将数据从 Dataframe 写入 Excel 工作表时出错
【发布时间】:2018-12-20 20:29:13
【问题描述】:

我有一个数据框,我正在尝试使用 xlsxwriter 模块将其写入 Excel 工作表。

下面是我的数据框的样子:

prod_id,prod_name,price,units
prod_a,apple,100,10
prod_b,mango,10,123
prod_c,orange,12,14

我正在尝试将上面的 Dataframe 写成 excel 如下:

# Pulling data for the sheet
row = 1
col = 0

# Iterate through the array you have and unpack the tuple at each index
for elm1, elm2, elm3, elm4 in df:
    worksheet.write(row, col, elm1, number_format)
    worksheet.write(row, col + 1, elm2, number_format)
    worksheet.write(row, col + 2, elm3, number_format)
    worksheet.write(row, col + 3, elm4, number_format)
    row += 1

会报错

for elm1, elm2, elm3, elm4 in df:
ValueError: too many values to unpack (expected 4)

【问题讨论】:

    标签: python python-3.x pandas xlsxwriter


    【解决方案1】:

    错误是因为,您正在使用多个变量循环 df。相反,您应该只使用一个变量。

    如果我理解正确,您可以像这样调整循环:

    for row in df.itertuples():
        elm1,elm2,elm3,elm4 = row[1], row[2], row[3], row[4]
        worksheet.write(row, col, elm1, number_format)
        worksheet.write(row, col + 1, elm2, number_format)
        worksheet.write(row, col + 2, elm3, number_format)
        worksheet.write(row, col + 3, elm4, number_format)
        row += 1
    

    这应该可行。

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 2021-04-16
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2017-03-30
      • 2015-11-18
      相关资源
      最近更新 更多