Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create empty workbook in memory openpyxl

from openpyxl import Workbook
book = Workbook()
for country in "IN US JP UK".split():
    book.create_sheet(title=country)

This creates 5 sheets with the first sheet being unwanted.

I know that I can do this:

book = Workbook()
us_ws = book.active
us_ws.title = "IN"
for country in "US JP UK".split():
    book.create_sheet(title=country)

Is there any short cut?

like image 497
Rahul Avatar asked Feb 04 '23 07:02

Rahul


1 Answers

From the (Docs)

A workbook is always created with at least one worksheet. You can get it by using the openpyxl.workbook.Workbook.active() property

So if you do not need the default sheet, you can delete it:

from openpyxl import Workbook

book = Workbook()
book.remove(book.active)
for country in "IN US JP UK".split():
    book.create_sheet(title=country)

This deletes the first sheet, which will be the default created sheet, before creating the desired sheets.

Or, as pointed out in comments, if you are OK with the caveats of a write-only workbook you can do:

from openpyxl import Workbook

book = Workbook(write_only=True)
for country  in "IN US JP UK".split():
    book.create_sheet(title=country )
like image 96
Stephen Rauch Avatar answered Feb 15 '23 07:02

Stephen Rauch