How to write two sheets in a single workbook at the same time using openpyxl

别等时光非礼了梦想. 提交于 2019-11-30 13:32:42

问题


I have to create and write a new excel workbook with about 5 worksheets. The purpose of my code is to read a database and split that into different sheets depending on certain criterion.

I have used the following code in python 2.7 using openpyxl-1.1.0

from openpyxl.workbook import Workbook
dest_filename = 'D:\\Splitted.xlsx'

wb = Workbook()
ws1 = wb.worksheets[0]
ws1.title = 'Criterion1'

ws2 = wb.worksheets[1]
ws2.title = 'Criterion2'

## Read Database, get criterion
if criterion == Criterion1:
    ws1.cell('A1').value = 'A1'
    ws1.cell('B1').value = 'B1'
elif criterion == Criterion2:
    ws2.cell('A1').value = 'A2'
    ws2.cell('B1').value = 'B2'

wb.save(filename = dest_filename)

I am able to write single sheet, but if I try to create 2nd worksheet, I am getting an error saying "Index out of range" at code ws2 = wb.worksheets[1]

Is there any solution to write 2 or more worksheets in a single workbook at the same time?


回答1:


You shouldn't try and access worksheets by index. The error is because the second worksheet hasn't been created (every workbook has a single worksheet created automatically).

ws1 = wb.active
ws2 = wb.create_sheet()

Should solve your problem.



来源:https://stackoverflow.com/questions/26328398/how-to-write-two-sheets-in-a-single-workbook-at-the-same-time-using-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!