How to write two sheets in a single workbook at th

2019-02-07 12:22发布

问题:

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.