Python openpyxl 如何在工作表中写入列表数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29354868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can openpyxl write list data in sheet?
提问by GuangWu
recently I am using openpyxl to deal with some scientific data, when I was writting the list data to a excel file, I have a problem.
最近在用openpyxl处理一些科学数据,在把list数据写入excel文件的时候,遇到了一个问题。
datalist[row][col]
wb=openpyxl.Workbook(optimized_write=Ture)
ws_write = wb.create_sheet(0)
for i in range(row):
ws_write.append([datalist[i][0]])
wb.save(filename='data.xlsx')
when it is done, seems like that it only can write the list into the first col of the xlsx file, how can I assign the same col of my datalist to the same col of xlsx file in the same sheet? Is there any reference to control the output?
完成后,似乎它只能将列表写入 xlsx 文件的第一个列,如何将数据列表的相同列分配给同一张表中 xlsx 文件的相同列?有没有控制输出的参考?
Thanks alot
非常感谢
回答by Alan Hoover
You are only writing the first column of your data (col=0). In order to include all the data, either add an internal loop:
您只写入数据的第一列(col=0)。为了包含所有数据,添加一个内部循环:
for i in range(row):
for j in range(col):
ws_write.append([datalist[i][j]])
wb.save(filename='data.xlsx')
or, write the entire row at a time:
或者,一次写入整行:
for i in range(row):
ws_write.append([datalist[i]])
wb.save(filename='data.xlsx')
I do not know that package to make sure that the output syntax is correct.
我不知道那个包来确保输出语法是正确的。
edit: after looking at this:Insert row into Excel spreadsheet using openpyxl in Pythonit appears that you need to do something like:
编辑:查看此内容后:在 Python 中使用 openpyxl 将行插入 Excel 电子表格中,您似乎需要执行以下操作:
for i in range(row):
for j in range(col):
ws_cell(row=i,col=j).value = datalist[i][j]
wb.save(filename='data.xlsx')
回答by Charlie Clark
When using ws.append(row)
you must insert pass in a whole either as sequence or as a generator. I don't understand your data structure but something like the following should work.
使用时,ws.append(row)
您必须将整个过程作为序列或生成器插入。我不明白你的数据结构,但像下面这样的东西应该可以工作。
for row in datalist:
ws.append(row)
If this is not sufficient then please provide more information about the structure of your data.
如果这还不够,请提供有关数据结构的更多信息。
回答by Raccoon_17
If I understood your question correctly, you would need something like this:
如果我正确理解你的问题,你需要这样的东西:
myList = ['First','Second','Third','Fourth','Fifth']
wb = xl.load_workbook('test.xlsx')
ws= wb.active
ws.append(myList)
This will append every item from the list on each column from same row.
这会将列表中的每个项目附加到同一行的每一列上。
Hope that helps :)
希望有帮助:)