Skip to content

Commit 91b3898

Browse files
committed
Make reading Excel sheets in DataTable more robust
1 parent 25179e5 commit 91b3898

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

webware/MiscUtils/DataTable.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
John 893-5901
1414
1515
This data often comes from delimited text files which typically
16-
have well defined columns or fields with several rows each of which can
16+
have well-defined columns or fields with several rows each of which can
1717
be thought of as a record.
1818
1919
Using a DataTable can be as easy as using lists and dictionaries::
@@ -202,6 +202,7 @@
202202

203203
from datetime import date, datetime, time, timedelta, tzinfo
204204
from decimal import Decimal
205+
from time import sleep
205206
from warnings import warn
206207

207208
from MiscUtils import NoDefault
@@ -249,8 +250,8 @@
249250

250251
def canReadExcel():
251252
try:
252-
from win32com.client import Dispatch # pylint: disable=import-error
253-
Dispatch("Excel.Application")
253+
from win32com import client # pylint: disable=import-error
254+
client.gencache.EnsureDispatch("Excel.Application")
254255
except Exception:
255256
return False
256257
return True
@@ -440,9 +441,19 @@ def canReadExcel():
440441
def readExcel(self, worksheet=1, row=1, column=1):
441442
maxBlankRows = 10
442443
numRowsToReadPerCall = 20
443-
from win32com.client import Dispatch # pylint: disable=import-error
444-
excel = Dispatch("Excel.Application")
445-
workbook = excel.Workbooks.Open(os.path.abspath(self._filename))
444+
from win32com import client # pylint: disable=import-error
445+
for _retry in range(40):
446+
try:
447+
excel = client.gencache.EnsureDispatch("Excel.Application")
448+
workbooks = excel.Workbooks
449+
except Exception:
450+
# Excel may be busy, wait a bit and try again
451+
sleep(0.125)
452+
else:
453+
break
454+
else:
455+
raise DataTableError('Cannot read Excel sheet')
456+
workbook = workbooks.Open(os.path.abspath(self._filename))
446457
try:
447458
worksheet = workbook.Worksheets(worksheet)
448459
worksheet.Cells(row, column)

0 commit comments

Comments
 (0)