简体   繁体   English

使用xlsxwriter将数据从Dataframe写入Excel工作表时出错

[英]Error writing data from Dataframe to excel sheet using xlsxwriter

I have a dataframe that I am trying to write to a excel sheet using xlsxwriter module. 我有一个要使用xlsxwriter模块写入Excel工作表的数据框。

Given below is the how my dataframe looks like: 以下是我的数据框的外观:

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

I am trying to write the above Dataframe to excel as below: 我正在尝试将上述数据框编写为如下所示的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

It throws an error 引发错误

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

The error is because, you are looping over df with multiple variables. 该错误是因为,您正在使用多个变量遍历df Instead, you should only one variable. 相反,您应该只使用一个变量。

If I understand correctly, you can tweak your loop something like this: 如果我理解正确,则可以调整循环,如下所示:

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

This should work. 这应该工作。

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

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