Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 773
Mallikarjun Avatar asked Oct 12 '14 18:10

Mallikarjun


People also ask

How do I write multiple sheets in Excel in Python?

To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique sheet_name . With all data written to the file it is necessary to save the changes.

How do I append a sheet in openpyxl?

Openpyxl append valuesWith the append method, we can append a group of values at the bottom of the current sheet. In the example, we append three columns of data into the current sheet. The data is stored in a tuple of tuples. We go through the container row by row and insert the data row with the append method.

How do I create multiple sheets in Excel VBA?

To add multiple sheets in one go, you just need to define the COUNT argument with the number of sheets you want to add. Now the count of the sheets that you have defined is 5, so when you run this code it instantly adds the five new sheets in the workbook.


1 Answers

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.

like image 156
Charlie Clark Avatar answered Oct 10 '22 12:10

Charlie Clark