-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxlcontext.py
More file actions
27 lines (20 loc) · 798 Bytes
/
xlcontext.py
File metadata and controls
27 lines (20 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class ExcelContext(object):
"""Manages a workbook opened in an Excel application through COM."""
def __init__(self, wkbookfile, wksheet=None, save=False):
self.file = wkbookfile
self.wksheet = wksheet
self.save = save
def __enter__(self):
from win32com.client import constants, DispatchEx
self.xlapp = DispatchEx('Excel.Application')
self.xlapp.Visible = False
self.wkbook = self.xlapp.Workbooks.Open(self.file)
if self.wksheet:
return self.wkbook.Worksheets(self.wksheet)
else:
return self.wkbook
def __exit__(self, exc_type, exc_val, exc_tb):
if self.save:
self.wkbook.Save()
self.wkbook.Close()
self.xlapp.Quit()