本文整理汇总了Python中win32com.client.Dispatch类的典型用法代码示例。如果您正苦于以下问题:Python Dispatch类的具体用法?Python Dispatch怎么用?Python Dispatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Dispatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: docFilter
def docFilter(fileList):
'''
转换word为txt,提取信息后清除txt.
'''
error_file = []
for f in fileList:
# fileName = f.split('\\')[-1].split('.')[-2].decode('gbk')
# filePath = ''.join(f.split('\\')[:-1]).decode('gbk')
f = os.path.realpath(f)
fileName = f.split('\\')[-1].split('.')[0]
print fileName.decode('gbk') + ' start ..'
print '-------------------------------------'
word = Dispatch("Word.Application")
# 后台静默运行
word.Visible = 0
word.DisplayAlerts = 0
try:
doc = word.Documents.Open(f,0,ReadOnly = 1)
saveFileTxt = re.sub('.doc','.txt',f).decode('gbk')
#保存为 txt 格式
doc.SaveAs(u'%s' % saveFileTxt ,7)
content = open(saveFileTxt,'r').read()
#开始过滤
pattern_result = Filter(content)
except Exception, E:
print E
error_file.append(f)
continue
finally:
示例2: save2xlsx
def save2xlsx(fname, output_dump=None):
"""
Do a simple : create empty xlsx, paste python list as content, save as given
fname, close and quit MS Excel
"""
from win32com.client import Dispatch
if output_dump is None:
output_dump = []
xlapp = Dispatch("excel.application")
xlapp.DisplayAlerts = False
xlapp.Visible = True
xlapp.ScreenUpdating = True
# create a new spreadsheet
xlbook = xlapp.Workbooks.Add()
# use the first worksheet
sht1 = xlbook.Sheets("Sheet1")
# inserts all the accepted claims
address = list2exceladdress(output_dump)
pprint(address)
ur1 = sht1.Range(address)
ur1.Value = output_dump
xlbook.SaveAs(fname) # save the spreadsheet
xlbook.Close() # close the workbook
xlapp.DisplayAlerts = True
xlapp.Quit() # quit Excel
示例3: __init__
def __init__(self,dc1,xlwb1,Hi,Me,Lo):
self.High=Hi
self.Medium=Me
self.Low=Lo
word = Dispatch('Word.Application')
xlApp = Dispatch("Excel.Application")
xlApp.Visible = True
self.doc1 = dc1
self.xlWb1 =xlwb1
self.xlSht1 = self.xlWb1.WorkSheets(3)
print "Please give path of second excel sheet"
print "\n"
self.xlWb2 =xlApp.Workbooks.Open(raw_input())
self.xlSht2 = self.xlWb2.WorkSheets(3)
print "Please give path and name to save file e.g C:\Users\inprsha\Desktop\hello.xlsx"
print "\n"
self.xlWb2.SaveAs(raw_input())
print "enter row no in which u want to fill details"
self.row_no=raw_input()
示例4: visit_job
def visit_job(id, sleep = 0.001 ):
try:
#urllib.urlopen('http://192.168.1.242:8080/').read()
start = time.time()
ie = Dispatch('InternetExplorer.Application')
ie.Visible = 0
url = 'http://blog.sina.com.cn/zgrwzj'
ie.Navigate(url)
state = ie.ReadyState
logger.debug("visit: %s", url)
while 1:
state = ie.ReadyState
if state ==4:
break
time.sleep(1)
state = None
# end
end = time.time()
run_time = end - start
t_str = " Elipse Time:%.2f s" % run_time
if ret == True:
r_str = "OK"
else:
r_str = "Failed"
r_str = r_str + '\t' + t_str
return r_str
except Exception, e:
#print '[%4d]' % id, sys.exc_info()[:2]
exstr = traceback.format_exc()
logger.debug("test_job exception:%s", exstr)
return "Exception"
示例5: run
def run(self):
try:
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
#tts = DispatchWithEvents("SAPI.SpVoice.1", SpeechEvents)
tts = Dispatch('SAPI.SpVoice')
except:
self.plugin.PrintError(self.plugin.text.errorCreate)
return
vcs = tts.GetVoices()
voices = [(voice.GetDescription(), voice) for voice in vcs]
tmp = [item[0] for item in voices]
ix = tmp.index(self.voiceName) if self.voiceName in tmp else 0
tts.Voice = voices[ix][1]
devs = tts.GetAudioOutputs()
devices = [(dev.GetDescription(), dev) for dev in devs]
tmp = [item[0] for item in devices]
ix = tmp.index(self.device) if self.device in tmp else 0
tts.AudioOutput = devices[ix][1]
tts.Rate = self.rate
tts.Volume = self.volume
tts.Speak(self.text,0)
suffix = self.plugin.text.suffix if self.suff == "" else "%s.%s" % (
self.plugin.text.suffix,
self.suff
)
self.plugin.TriggerEvent(suffix)
示例6: connection
def connection ():
global _connection
if _connection is None:
_connection = Dispatch ("ADODB.Connection")
_connection.Provider = "ADsDSOObject"
_connection.Open ("Active Directory Provider")
return _connection
示例7: StartChemDraw
def StartChemDraw(visible=True, openDoc=False, showDoc=False):
""" launches chemdraw """
global cdApp, theDoc, theObjs, selectItem, cleanItem, centerItem
if cdApp is not None:
# if called more than once, do a restart
holder = None
selectItem = None
cleanItem = None
centerItem = None
theObjs = None
theDoc = None
cdApp = None
cdApp = Dispatch('ChemDraw.Application')
if openDoc:
theDoc = cdApp.Documents.Add()
theObjs = theDoc.Objects
else:
theDoc = None
selectItem = cdApp.MenuBars(1).Menus(2).MenuItems(8)
cleanItem = cdApp.MenuBars(1).Menus(5).MenuItems(6)
if _cdxVersion == 6:
centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(1)
else:
centerItem = cdApp.MenuBars(1).Menus(4).MenuItems(7)
if visible:
cdApp.Visible = 1
if theDoc and showDoc:
theDoc.Activate()
示例8: __init__
def __init__(self, databasename):
global connection, command
connection = Dispatch("ADODB.Connection")
command = Dispatch("ADODB.Command")
connection.Open(ADOdb.dsource % databasename)
command.ActiveConnection = connection
示例9: excel_open
def excel_open(file_name):
try:
excel = Dispatch('Excel.Application')
excel.Visible = False #If we want to see it change
data_sheet = excel.Workbooks.Open(file_name)
#Activate Excel Parts
workBook = excel.ActiveWorkbook
activeSheet = excel.ActiveSheet
sheets = workBook.Sheets
return sheets, workBook
except:
print '(' + str(clock(0)) + ') ERROR: Failed to initalize workbook. Retrying...'
try:
excel_close(workBook)
except:
pass
try:
excel = Dispatch('Excel.Application')
excel.Visible = False #If we want to see it change
data_sheet = excel.Workbooks.Open(file_name)
#Activate Excel Parts
workBook = excel.ActiveWorkbook
activeSheet = excel.ActiveSheet
sheets = workBook.Sheets
return sheets, workBook
except:
print '(' + str(clock(0)) + ') ERROR: Failed to initialize workbook on second try.'
return False, False
示例10: get_table_box
def get_table_box(self, targetSheet, startRow, endRow, startCol, endCol):
"""
startRow, Starts at 1, not 0!
endRow, Inclusive
startCol, Starts at 1
endCol Inclusive
"""
logging.debug("Loading table on {}".format(targetSheet))
raise
# Attach the excel COM object
xl = Dispatch('Excel.Application')
# Open the project file
book = xl.Workbooks.Open(self.excelPath)
# Select the sheet
sheet = book.Sheets(targetSheet)
xl.Visible = False
rows = list()
for row in range(startRow,endRow+1):
rows.append(list())
for col in range(startCol, endCol+1):
thisVal = sheet.Cells(row,col).Value
rows[-1].append(thisVal)
book.Close(SaveChanges=0) #to avoid prompt
return rows
示例11: toExcel
def toExcel(self):
#Instantiate win32com client excel object and create common objects
xl = Dispatch("Excel.Application")
xl.Visible = True
xl.Workbooks.Add()
wb = xl.ActiveWorkbook
shts = wb.Sheets
#Check for file with current path and name, change it if need be, save it
checker = CheckFilename(self.o_path, self.filename)
filename = checker.checkName()
wb.SaveAs(filename)
shts("Sheet1").Delete
shts("Sheet2").Delete
shts("Sheet3").Delete
keys = self.output.keys()
for sheet in keys:
xl.Worksheets.Add().Name = sheet
sht = shts(sheet)
r,c = 1,1
export = self.output[sheet]
for row in export:
c = 1
for cell in row:
sht.Cells(r,c).Value = cell
c+=1
r+=1
xl.ActiveWorkbook.Save()
示例12: __init__
def __init__(self, parent, width, height):
"""Initiate the video player
Arguments
parent -- the parent frame of this video player
width -- the width of this video player
height -- the height of this video player
"""
tki.Frame.__init__(self, parent, width = width, height = height)
#self.grid(sticky = tki.W + tki.N + tki.E + tki.S)
self.grid_propagate(0)
hwnd = self.winfo_id()
windll.atl.AtlAxWinInit()
fwnd = windll.user32.CreateWindowExA(0, 'AtlAxWin', 0, 0x50000000, 0, 0, width, height, hwnd, 0, 0, 0)
if(fwnd == 0):
error = windll.kernel32.GetLastError()
#wmp = DispatchWithEvents('WMPlayer.OCX', WMPEvents)
wmp = Dispatch('WMPlayer.OCX')
self._wmp = wmp
wmp_addr = int(repr(wmp._oleobj_).split()[-1][2:-1], 16)
windll.atl.AtlAxAttachControl(wmp_addr, fwnd, 0)
wmp.uiMode = 'mini'
wmp.enableContextMenu = False
global clickHandler
clickHandler = self._togglePlayer
示例13: gen_excel
def gen_excel(self, rows):
f = os.getcwd() + "\\" + "tmp" + repr(rows) +'.xls'
if os.path.exists(f):
os.remove(f)
shutil.copy("send.xls", f)
rows += 1
f_open = (f)
xlsApp = Dispatch("Excel.Application")
xlsApp.Visible = False
xlsBook = xlsApp.Workbooks.Open(f_open)
sheet_name = u'工资表模板'
#print (sheet_name)
writeSht = xlsBook.Worksheets(sheet_name)
to_addr = self.readSht.Cells(rows, self.mailCol).Value
print(to_addr)
for j in range(1,23):
if j == self.mailCol:
continue
writeSht.Cells(2,j + 1).Value = self.readSht.Cells(rows, j).Value
#print (writeSht.Cells(6,j).Value)
xlsBook.Close(SaveChanges=1)
#xlsApp.Quit()
return to_addr
示例14: __init__
def __init__(self, path,docfile,xml):
self.path = path
word = Dispatch('Word.Application')
word.Visible=False
self.xml=xml
# self.doc1=word.Documents.Open(os.path.join(os.getcwd(), 'MARS.doc'))
self.doc1=word.Documents.Open(docfile)
示例15: navigate
def navigate(self):
self.v_result.id = self.task_id
try:
logger.debug("task_id=%3d, worker=%2d, visit=%s" % (self.task_id, self.worker_id, self.dest_host))
start = int(time.time())
ie = Dispatch('InternetExplorer.Application')
ie.Visible = 0
ie.Navigate(self.dest_host)
state = ie.ReadyState
count = 0
while 1:
state = ie.ReadyState
if state == 4:
self.v_result.result = 'OK'
self.v_result.code = 0
break
if count > self.timeout:
self.v_result.result = 'Timeout'
self.v_result.code = 1
break
time.sleep(1)
count = count + 1
end = int(time.time())
self.v_result.consume_time = end - start
state = None
ie.Quit()
ie = None
del ie
except Exception, e:
exstr = traceback.format_exc()
print exstr
self.v_result.result = 'Exception'
self.code = 3