Winand

ie js inject, excel workbook monitor

Feb 2nd, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from win32com.client import DispatchWithEvents, Dispatch
  4. from time import sleep as sleep_
  5. import pythoncom
  6. recode = lambda e: e.decode('utf-8').encode('cp1251') #utf-8 -> cp1251
  7.  
  8. supress_alert = "ОТЧЕТ ПОСТРОЕН" #supress all alerts with this string
  9. js_alert = """if(window["alert_"] == undefined) {
  10.                alert_ = alert;
  11.                alert = function(e) {
  12.                    if(e.indexOf("%s") == -1)
  13.                        alert_(e)
  14.                }
  15.            }""" % recode(supress_alert)
  16. wb_def_name = recode("Книга") #Default Excel workbook name
  17.  
  18. class IEEvents:
  19.     def OnDocumentComplete(self, pDisp, URL):
  20.         pDisp = Dispatch(pDisp)
  21.         if URL.endswith("new  2.html"):
  22.             try:
  23.                 pDisp.Document.parentWindow.execScript(js_alert)
  24.                 print "Info. Alerts supressed on", URL
  25.             except Exception as e:
  26.                 if e.excepinfo[-1] & 0xffffffff == 0x80070005:
  27.                     print "Error. Internet explorer blocked content."
  28.                 else: print e
  29.  
  30. # ie = DispatchWithEvents("InternetExplorer.Application", IEEvents)
  31. # ie.Visible = 1
  32.  
  33. def sleep(sec):
  34.     sleep_(sec)
  35.     pythoncom.PumpWaitingMessages()
  36.    
  37. def waitForWorkbook():
  38.     print "Info. Waiting for workbook..."
  39.     context, rot = pythoncom.CreateBindCtx(0), pythoncom.GetRunningObjectTable()
  40.     found, hashes = False, []
  41.     while not found:
  42.         for i in rot:
  43.             hash = i.Hash()
  44.             if hash not in hashes:
  45.                 hashes.append(hash)
  46.                 print "checking", i.GetDisplayName(context, None)
  47.                 if i.GetDisplayName(context, None).startswith(wb_def_name):
  48.                     obj = rot.GetObject(i)
  49.                     wb = Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch))
  50.                     if not wb.Parent.Visible:
  51.                         print "Info. Workbook found -", wb.Name
  52.                         found = True
  53.                         break
  54.         sleep(0.05)
  55.     print "Info. Waiting for script to finish..."
  56.     while not wb.Parent.Visible:
  57.         sleep(0.05)
  58.     return wb
  59.  
  60. wb = waitForWorkbook()
  61. print "Now save workbook", wb.Name
Advertisement
Add Comment
Please, Sign In to add comment