Python:将列表移动到 Excel 中的一行并使用 openpyxl 进行追加

问题描述 投票:0回答:1

我尝试将包含列表的行附加到 Excel 电子表格并收到以下错误: ValueError:无法转换[0.894、0.566、0.483、0.27、0.266、0.268、0.269、0.161、0.16、0.157、0.269、0.284、0.272、0.261、0.252、0.227、0 .22、0.222、0.225、0.239、0.251、0.257、 0.302, 0.292, 0.272, 0.272, 0.256, 0.224, 0.334] 到 Excel 我通过分别引用每个列表元素来修复代码,如下所示。这可行,但代码非常笨拙。有没有更好的方法来做到这一点(我是Python新手)?

new_row = [' ', sa_length, pln[0], pln[1], pln[2], pln[3], pln[4], pln[5], pln[6], pln[7], pln[8], pln[9], pln[10],
pln[11], pln[12], pln[13], pln[14], pln[15], pln[16], pln[17], pln[18], pln[19], pln[20],
pln[21], pln[22], pln[23], pln[24], pln[25], pln[26], pln[27], pln[28],
pln_max, rect[0], rect[1], rect[2], rect[3],
edge1[0], edge1[1], edge1[2], edge1[3], edge1[4], edge1[5], edge1[6],
middle[0], middle[1], middle[2], middle[3], middle[4], middle[5], middle[6], 
edge2[0], edge2[1], edge2[2], edge2[3], edge2[4], edge2[5], edge2[6]]

#add a new row to the output excel file
ws_out.append(new_row)

代码成功将该行追加到现有 Excel 文件中

python append openpyxl
1个回答
0
投票

您似乎正在尝试使用 Openpyxl 追加将列表列表添加到工作表中,
即由其他列表组成的列表

listA = [[list1], [list2],[list3]...]

尝试使用append as 来写入“listA”

ws.append(listA)

将导致出现错误

ValueError: Cannot convert <list> to excel
,其中列表是第一个列表。

您的假设*我通过单独引用每个列表元素来修复代码*是正确的,但您可以使用 for 循环从列表列表中提取每个单独的列表并应用。
由于 Openpyxl 追加的工作方式,每个列表都会添加到下一个未使用的行。

代码示例(为了清楚起见,我创建了一个名为“listA”的简化列表,其中包含三个列表,每个列表有 7 个项目。

import openpyxl

### List of lists, 3 lists  
listA = [[0.302, 0.292, 0.272, 0.272, 0.256, 0.224, 0.334],
         [1.302, 1.292, 1.272, 1.272, 1.256, 1.224, 1.334],
         [2.302, 2.292, 2.272, 2.272, 2.256, 2.224, 2.334]
         ]

xlfile = 'foo.xlsx'
wb = openpyxl.load_workbook(xlfile)
ws = wb['Sheet1']

### If I was to run ws.append(listA) here the error would be returned 
### ValueError: Cannot convert [0.302, 0.292, 0.272, 0.272, 0.256, 0.224, 0.334] to Excel

### Use for loop to extract each list.
for row_data in listA:
    ws.append(row_data)  # Append each list individually 

wb.save(xlfile)

结果

© www.soinside.com 2019 - 2024. All rights reserved.