![](/img/trans.png)
[英]Is it possible to read data from an Excel sheet in Python using Xlsxwriter? If so how?
[英]Error writing data from Dataframe to excel sheet using xlsxwriter
我有一個要使用xlsxwriter模塊寫入Excel工作表的數據框。
以下是我的數據框的外觀:
prod_id,prod_name,price,units
prod_a,apple,100,10
prod_b,mango,10,123
prod_c,orange,12,14
我正在嘗試將上述數據框編寫為如下所示的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)
該錯誤是因為,您正在使用多個變量遍歷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
這應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.