Excel Concluded
Having been through the mechanics, we will now build a class to make it slightly easier to get data in and out of Excel. It’s easy already, but if you want to do a lot of work with Excel, you can certainly save a few lines of code in the users’ scripts. An example of this can be found in the file exceldemos.py.
We’ve created a class called
easyExcel
. When an instance is created, it starts
Excel. This class provides methods to open, create, and save files,
and to get and set cell values and ranges. It can also deal with the
Unicode strings and time objects if you wish. You could easily extend
it to add new methods, but here are a selection that should be
useful:
class easyExcel:
"""A utility to make it easier to get at Excel. Remembering
to save the data is your problem, as is error handling.
Operates on one workbook at a time."""
def __init__(self, filename=None):
self.xlApp = win32com.client.Dispatch('Excel.Application')
if filename:
self.filename = filename
self.xlBook = self.xlApp.Workbooks.Open(filename)
else:
self.xlBook = self.xlApp.Workbooks.Add()
self.filename = ''
def save(self, newfilename=None):
if newfilename:
self.filename = newfilename
self.xlBook.SaveAs(newfilename)
else:
self.xlBook.Save()
def close(self):
self.xlBook.Close(SaveChanges=0)
del self.xlAppNow put in methods to set and get cells. Users can specify a sheet name or index, row, and column:
def getCell(self, sheet, row, col): "Get value of one cell" sht = self.xlBook.Worksheets(sheet) return ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access