How can openpyxl write list data in sheet?

2020-02-29 03:46发布

问题:

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.

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?

Thanks alot

回答1:

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.

for row in datalist:
    ws.append(row)

If this is not sufficient then please provide more information about the structure of your data.



回答2:

You are only writing the first column of your data (col=0). In order to include all the data, either add an internal loop:

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 Python it appears that you need to do something like:

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')