How to write two sheets in one book at the same time using openpyxl
I need to create and write a new Excel workbook with about 5 worksheets. The purpose of my code is to read the database and split it into different sheets based on a 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 can write a separate sheet, but if I try to create a 2nd sheet, I get an "Specify out of range" error in the code ws2 = wb.worksheets [1]
Is there any solution for writing two or more sheets in one book at the same time?
+3
Mallikarjun
source
to share
1 answer
You shouldn't try to access sheets by index. The error is that the second worksheet was not created (each workbook has one automatically generated worksheet).
ws1 = wb.active
ws2 = wb.create_sheet()
Your problem needs to be resolved.
+4
Charlie clark
source
to share