zakparks31191
zakparks31191

Reputation: 937

Is there a way to get the name of a workbook in openpyxl

There is a worksheet.title method but not workbook.title method. Looking in the documentation there is no explicit way to find it, I wasn't sure if anyone knew a workaround or trick to get it.

Upvotes: 6

Views: 16986

Answers (2)

James McIntyre
James McIntyre

Reputation: 116

Had this problem myself, John Clements' answer that this property doesn't exist was useful!

I found what I think to be a good solution, while this property isn't there. At the point of loading the file, instead of giving the file name as a string, first set the file name in a veriable and then load the file using this veriable. You can then amend the workbook class you get from loading the workbook with a new property and you can set this property to the file name veriable. This way, no matter how far down you pass this class inside functions, you have the file name without having to pass it seperatly.

e.g.

from openpyxl import load_workbook

file = 'file_name_here.xlsx'

wb = load_workbook(file, read_only = False)

wb.name = file

Would definetly be handy if OpenPyXL implamented this feature and had it so that wb.save() worked without an input perameter. (I've not yet done a PR to an open source project yet and don't feel confident enough yet so I don't mean to complain)

Not sure if this should be a seperate answer or should have been a comment on Jon's answer but here we are.

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142226

A workbook doesn't really have a name - normally you'd just consider it to be the basename of the file it's saved as... slight update - yep, even in VB WorkBook.Name just returns "file on disk.xls"

Upvotes: 3

Related Questions