Reputation: 447
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)
Upvotes: 0
Views: 97
Reputation: 34056
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.
Upvotes: 1