简体   繁体   中英

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.

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:

# 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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