def xme2mga(path_xme, path_mga): # use abspath, since on GME x64-only, parser will be called out-of-proc (which won't share the same cwd) abspath_xme = os.path.abspath(path_xme) abspath_mga = os.path.abspath(path_mga) xme = DispatchEx('Mga.MgaParser') (paradigm, parversion, parguid, basename, ver) = xme.GetXMLInfo(abspath_xme) mga = DispatchEx('Mga.MgaProject') resolver = DispatchEx('Mga.MgaResolver') try: resolver.IsInteractive = False xme.Resolver = resolver except AttributeError: # Older GME pass # create_project(mga, 'MGA=' + abspath_mga, paradigm) mga.Create('MGA=' + abspath_mga, paradigm) try: xme.ParseProject(mga, path_xme) except Exception: mga.Close(True) raise mga.Save('MGA=' + abspath_mga)
def __init__(self, canalyzer_config_path, canape_config_path, baud_rate, a2l_path, capl_path=None, channel=2, device_type="CCP", logger=None): self.logger = logger or logging.getLogger(__name__) self._capl_funcs = {} self._capl_path = capl_path if self._capl_path is not None: self._capl_names = self._get_capl_fun_names() self._CANalyzer = DispatchEx('CANalyzer.Application') self._CANalyzer.Open(canalyzer_config_path) self._CANalyzer.CAPL.Compile() global CANalyzer CANalyzer = self event_handler = win32com.client.WithEvents(self._CANalyzer.Measurement, MeasEvents) self._CANalyzer.UI.Write.Output('measurement starting...') self._CANalyzer.Measurement.Start() while (not self._CANalyzer.Measurement.Running): time.sleep(1) self._CANalyzer.UI.Write.Output('measurement started...') self.logger.info("Canalyzer measurement started.") # init the CANape self._Canape = DispatchEx('CANape.Application') self._Canape.Open1(canape_config_path, 1, baud_rate, True) self._CanapeDev = self._Canape.Devices.Add(device_type, a2l_path, device_type, channel) pass
def Excel_CatchScreen(filename, sheetname, screen_area, img_name=False): """ 对excel的表格区域进行截图——用例:excel_catch_screen(ur"D:\Desktop\123.xlsx", "Sheet1", "A1:J10")""" pythoncom.CoInitialize() # excel多线程相关 excel = DispatchEx("Excel.Application") # 启动excel excel.Visible = True # 可视化 excel.DisplayAlerts = False # 是否显示警告 wb = excel.Workbooks.Open(filename) # 打开excel ws = wb.Sheets(sheetname) # 选择sheet ws.Range(screen_area).CopyPicture() # 复制图片区域 ws.Paste() # 粘贴 ws.Paste(ws.Range('B1')) # 将图片移动到具体位置 name = str(uuid.uuid4()) # 重命名唯一值 new_shape_name = name[:6] excel.Selection.ShapeRange.Name = new_shape_name # 将刚刚选择的Shape重命名,避免与已有图片混淆 ws.Shapes(new_shape_name).Copy() # 选择图片 img = ImageGrab.grabclipboard() # 获取剪贴板的图片数据 if not img_name: img_name ='./pic/' + name + ".PNG" img.save(img_name) # 保存图片 wb.Close(SaveChanges=0) # 关闭工作薄,不保存 excel.Quit() # 退出excel pythoncom.CoUninitialize() return name + ".PNG" #if __name__ == '__main__': #pass #ImageName = Excel_CatchScreen("D:/alog/天津仓/Algorithm/Dingtalk/PictureBroadcast/DingtalkChatbot-master/dingtalkchatbot/datareport.xls", "hour", "A1:C25")
def excel_catch_screen(os_path,file_name, sheet_name, screen_area,picture_name): excel = DispatchEx("Excel.Application") #启动excel excel.Visible = True #可视化 excel.DisplayAlerts = False #是否显示警告 wb = excel.Workbooks.Open(os_path+file_name) #打开excel ws = wb.Sheets(sheet_name) #选择sheet #拆分截频区域和图片名称 screen_area=screen_area.split(",") picture_name=picture_name.split(",") #循环处理每个截图区域 for i in range (0,len(screen_area)): ws.Range(screen_area[i]).CopyPicture() #复制图片区域 time.sleep(2) ws.Paste() #粘贴 excel.Selection.ShapeRange.Name = picture_name[i] #将刚刚选择的Shape重命名,避免与已有图片混淆 ws.Shapes(picture_name[i]).Copy() # 选择图片 time.sleep(2) img = ImageGrab.grabclipboard() # 获取剪贴板的图片数据 img_name = picture_name[i]+ ".PNG" #生成图片的文件名 img.save(os_path+img_name) #保存图片 time.sleep(1) wb.Close(SaveChanges=0) #关闭工作薄,不保存 excel.Quit() #退出excel
def excel_catch_screen(filename, sheetname, screen_area, img_name=False): """ 对excel的表格区域进行截图——用例:excel_catch_screen(ur"D:\Desktop\123.xlsx", "Sheet1", "A1:J10")""" pythoncom.CoInitialize() # excel多线程相关 excel = DispatchEx("Excel.Application") # 启动excel excel.Visible = True # 可视化 excel.DisplayAlerts = False # 是否显示警告 wb = excel.Workbooks.Open(filename) # 打开excel ws = wb.Sheets(sheetname) # 选择sheet ws.Range(screen_area).CopyPicture() # 复制图片区域 ws.Paste() # 粘贴 ws.Paste(ws.Range('B1')) # 将图片移动到具体位置 #name = str(uuid.uuid4()) # 重命名唯一值 #new_shape_name = name[:6] name = 'test' #图片名称 new_shape_name=name excel.Selection.ShapeRange.Name = new_shape_name # 将刚刚选择的Shape重命名,避免与已有图片混淆 ws.Shapes(new_shape_name).Copy() # 选择图片 img = ImageGrab.grabclipboard() # 获取剪贴板的图片数据 if not img_name: img_name = "E:\\cango\\"+name + ".PNG" img.save(img_name) # 保存图片 wb.Close(SaveChanges=0) # 关闭工作薄,不保存 excel.Quit() # 退出excel time.sleep(3) pythoncom.CoUninitialize()
def open_ie(url, size=(900, 680)): """打开IE浏览器""" width, height = size ie = DispatchEx('InternetExplorer.Application') # 设置窗口style ie.Visible = 1 ie.ToolBar = 0 ie.AddressBar = 0 ie.MenuBar = 0 ie.StatusBar = 0 ie.Resizable = 0 ie.Width = width ie.Height = height # 设置打开的 URL ie.Navigate(url) win32gui.SetForegroundWindow(ie.HWND) #win32gui.SetWindowPos(ie.HWND, win32con.HWND_TOPMOST, win32gui.SetWindowPos( ie.HWND, 0, 0, 0, width, height, win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER | win32con.SWP_SHOWWINDOW) return ie
def compare(self): self.excel = DispatchEx('Excel.Application') self.excel.Visible = False self.logger.info('excel initial setup') self.logger.info('new file '+self.file_new) self.logger.info('old file '+self.file_old) wbB=self.excel.Workbooks.Open(self.file_old) wbA=self.excel.Workbooks.Open(self.file_new) self.logger.info('open excels') wsA = wbA.worksheets("Sheet0") wsB = wbB.worksheets("Sheet0") wsA_used_row = wsA.usedrange.rows.count wsB_used_row = wsB.usedrange.rows.count #only compare first 9 columns used_col = 9 self.logger.info('initialize variables') self.logger.info('start comparing') for i in xrange(1, wsA_used_row+1): for j in xrange(1, used_col+1): #if bits number is different if wsA.Cells(i,j).Value != wsB.Cells(i,j).Value: wsA.Cells(i,j).Interior.Colorindex = 4 self.logger.info('end comparing') wbB.Close(False) self.excel.Visible = True
def doc2pdf(input, output): global w w = DispatchEx("Word.Application") w.Visible = False w.DisplayAlerts = False doc = w.Documents.Open(input, ReadOnly=1) doc.ExportAsFixedFormat(output, 17, False, 1)
def __init__(self, ast): GenericASTTraversal.__init__(self, ast) msword = DispatchEx('Word.Application') msword.Visible = 1 # 1表示要顯示畫面,若為0則不顯示畫面。 self.word = msword self.doc = msword.Documents.Add() # 開啟一個新的文件。 self.range = self.doc.Range() # 設定字型為標楷體 self.range.Font.Name = u"標楷體".encode('cp950') self.preorder() ti = 1 # title line number # Format Title if ast.title: para = self.doc.Paragraphs.First para.Format.Alignment = 1 # center para.Range.Select() msword.Selection.Font.Size = 18 msword.Selection.Font.Bold = 1 if ast.title.count('\n') == 1: para = self.doc.Paragraphs(2) para.Format.Alignment = 1 # center para.Range.Select() msword.Selection.Font.Size = 18 msword.Selection.Font.Bold = 1 ti = 2 try: history = ast.attrs[u'訂定'] + u'函訂定' para = self.doc.Paragraphs(ti + 1) para.Format.Alignment = 2 # center para.Range.Select() msword.Selection.Font.Size = 10 except KeyError, k: pass
def excel2pdf(input, output): global w w = DispatchEx("Excel.Application") w.Visible = False w.DisplayAlerts = False doc = w.Workbooks.Open(input, ReadOnly=1) doc.ExportAsFixedFormat(0, output)
def createIntergateFile(self): ''' 由模板创建工单综合实施文档 ''' self.order_info['ver'] = self.getVer(self.order_info['svn'], self.order_info['order_name'], 'Aeg2DB_Build') #print(self.order_info['ver']) self.intergrate_info['intergrate_file'] = os.path.join( self.order_info['svn'], 'Aeg2DB_' + self.order_info['ver'] + '.0_' + self.order_info['order_name'] + '_综合实施文档.docx') #由模板文件复制成实施文档 shutil.copy(self.intergrate_info['template_file'], self.intergrate_info['intergrate_file']) #启动独立的进程 w = DispatchEx('Word.Application') #后台运行,不显示,不警告 w.Visible = 0 w.DisplayAlerts = 0 #打开新的文档 doc = w.Documents.Open(self.intergrate_info['intergrate_file']) w.Selection.Find.ClearFormatting() w.Selection.Find.Replacement.ClearFormatting() w.Selection.Find.Execute('{ver}', False, False, False, False, False, True, 1, True, self.order_info['ver'], 2) w.Selection.Find.Execute('{order_name}', False, False, False, False, False, True, 1, True, self.order_info['order_name'], 2) doc.Close() w.Quit()
def merge_excels(): pythoncom.CoInitialize() xlApp = DispatchEx('Excel.Application') xlApp.Visible = False xlApp.DisplayAlerts = 0 xlApp.ScreenUpdating = 0 file = xlwt.Workbook() ta = file.add_sheet('sheet1') index = 0 try: excels = os.listdir(".//files") except: print 'can not find directory files' return for xfile in excels: indexMark = index if xfile[0] == '~': continue postfix = xfile.split(".")[-1] if postfix == "xls" or postfix == "xlsx": print "Merging " + xfile absPath = os.path.abspath(r"files\\" + xfile) index = xlrd_merge(index, absPath, ta) if (index == indexMark): index = win32com_merge(index, absPath, xlApp, ta) index = index - 1 file.save("merged.xls") xlApp.Quit() pythoncom.CoUninitialize()
def __init__(self, server, file): print('init mail client') # self.session = DispatchEx('Notes.NotesSession') # # self.server = self.session.GetEnvironmentString("MailServer", True) # self.db = self.session.GetDatabase(server, file) # if not self.db.IsOpen: # print('open mail db') # try: # self.db.OPENMAIL # except Exception as e: # print(str(e)) # print( 'could not open database: {}'.format('\mail\张丽华') ) # for notes 8.5 maybe self.session = DispatchEx('Notes.NotesSession') self.server = self.session.GetEnvironmentString("MailServer", True) self.db = self.session.GetDatebase(server, file) self.db.OPENMAIL print("11111111111111111111") print("2222222222222222") print(server) print(file) if not self.db.IsOpen: print("3333333333333333333333") try: self.db.Open() except pywintypes.com_error: print('could not open database: ')
def ddefunc(datahubname, topic, filename, txtname): pythoncom.CoInitialize() xlApp = DispatchEx("Excel.Application") xlApp.Visible = 0 # 隐藏 xlApp.Application.DisplayAlerts = 0 # 禁止弹出会话 nChan = xlApp.Application.DDEInitiate(datahubname, topic) # datahub名称 arrname = Opentxt(filename).split(",") # tagname timestamp = timefunc() # timestamp if(os.path.exists(txtname)): os.remove(txtname) for i in arrname: DDEVALUE = xlApp.DDErequest(nChan, i) if not DDEVALUE[0]: linex = 'TAGNAME='+i.replace(".Value", "") + '\n' liney = 'ITEM=VALUE,VALUE={},TIMESTAMP={},QUALITY=192'.format( 0, timestamp) + '\n' linez = linex+liney else: # dde = DDE.DDEClient(datahubname, topic) # if(os.path.exists(txtname)): # os.remove(txtname) # for i in arrname: # # repi = i.replace(".value", "") # DDEVALUE = dde.request(i) # print(DDEVALUE) linex = 'TAGNAME='+i.replace(".Value", "") + '\n' liney = 'ITEM=VALUE,VALUE={},TIMESTAMP={},QUALITY=192'.format( DDEVALUE[0], timestamp) + '\n' linez = linex+liney # print(linez) with open(txtname, "a+") as f: f.write(linez) xlApp.Quit() pythoncom.CoUninitialize()
def convert_excel_htm(self, local_file_path, new_file_name, file_path): """保存,以htm后缀存取""" # from win32com.client import Dispatch from win32com.client import DispatchEx import pythoncom # from win32com.client import constants pythoncom.CoInitialize() xl = DispatchEx('Excel.Application') # xl = Dispatch('Excel.Application') xl.DisplayAlerts = False wb = xl.Workbooks.Open(local_file_path) # 创建新的文件夹用来装转后的htm文件(一个网页一个文件夹) uti = Utillity() only_id = uti.get_nextval() file_dir = os.path.join(file_path, str(only_id), os.path.splitext(new_file_name)[0]) if not os.path.exists(file_dir): os.makedirs(file_dir) t_path = os.path.join(file_dir, os.path.splitext(new_file_name)[0]) print(t_path) wb.SaveAs(t_path, FileFormat=44) # 保存在Z盘 新文件夹下, constants.xlHtml==44 # xl.Application.Run("SaveHTML") xl.Workbooks.Close() xl.Quit() del xl return file_dir
def save_img(self,file,month_info,send_info): '''根据每个住户对应的租金,在截图xlsx文件修改数值,然后截图保存 :param file: 截图.xlsx :param month_info: 所有住户此月的租金信息dict :param send_info: 全部住户的租金信息(用于微信发送) :return: ''' file_name = os.path.abspath(file) # 把相对路径转成绝对路径 pythoncom.CoInitialize() # 开启多线程 excel = DispatchEx('excel.application')# 创建Excel对象 excel.visible = False # 不显示Excel excel.DisplayAlerts = 0 # 关闭系统警告(保存时不会弹出窗口) workbook = excel.workbooks.Open(file_name)# 打开截图.xlsx wSheet = workbook.worksheets['截图'] # 循环每个住户的数据,根据 所选月份,得到具体数据,然后再截图xlxs上改变数字,截图保存,添加到send_info for the_zuhu,the_month_data in month_info.items(): #该住户此月的租金信息不为空 if type(the_month_data)!=int: img_name = self.month + ':' + the_zuhu #该住户此月的截图名 self.change_sheet(wSheet, the_month_data) #根据不同住户 改变截图xlsx 里的 每个项目的金额 self.snapshot(excel, wSheet, img_name)#截图,保存 send_info[the_zuhu] = [the_month_data['租户'],the_month_data['合计'], img_name + '.png'] #格式:{住户A:[租户名,合计租金,图片名称],住户B....} else: send_info[the_zuhu]=0 workbook.Close(False) # 关闭Excel文件,不保存 excel.Quit() # 退出Excel pythoncom.CoUninitialize() # 关闭多线程
def open(self, init_path_name): print("PowerPoint open for %s" % init_path_name) self.__w = DispatchEx("PowerPoint.Application") try: self.__ppt = self.__w.Presentations.Open(init_path_name, ReadOnly=True, WithWindow=False) except pywintypes.com_error as e: raise FileOpenFailedException("Open PowerPoint file failed.")
def open_excelCOMS(excelfilename): ''' Opens the Excel COM object and returns a reference to that object as well as the Excel book ''' pythoncom.CoInitialize() excel = DispatchEx('Excel.Application') book = excel.Workbooks.Open(path.abspath(excelfilename)) return excel, book
def __init__(self, excelFile): ''' Parameters file: str, excel file ''' CoInitialize() self.excelCOM = DispatchEx('Excel.Application') self.excelBook = self.excelCOM.Workbooks.Open(excelFile)
def __init__(self): # kill_cilent() # pythoncom.CoInitialize() # 多线程初始化 self.excel = DispatchEx("Excel.Application") # 启动excel self.excel.Visible = True # 可视化 self.excel.DisplayAlerts = False # 是否显示警告 self.workbooks = None self.worksheet = None
def __validate_QTP(host): try: pythoncom.CoInitialize() DispatchEx('QuickTest.Application', host.get_ip()) pythoncom.CoUninitialize() return True except Exception as e: configuration_log.info(e) return False
def send_mail(subject, body_text, sendto, copyto=None, blindcopyto=None, attach=None): # Get credentials mailServer = 'Your Server' mailPath = 'Your database' mailPassword = '******' # Connect notesSession = DispatchEx('Lotus.NotesSession') try: notesSession.Initialize(mailPassword) notesDatabase = notesSession.GetDatabase(mailServer, mailPath) except pywintypes.com_error: raise Exception('Cannot access mail using %s on %s' % (mailPath, mailServer)) # print('Title:' + notesDatabase.Title) # Get a list of folders # for view in notesDatabase.Views: # if view.IsFolder: # print('view : ' + view.Name) document = notesDatabase.CreateDocument() document.ReplaceItemValue("Form", "Memo") document.ReplaceItemValue("Subject", subject) # assign random uid because sometimes Lotus Notes tries to reuse the same one uid = str(uuid.uuid4().hex) document.ReplaceItemValue('UNIVERSALID', uid) # "SendTo" MUST be populated otherwise you get this error: # 'No recipient list for Send operation' document.ReplaceItemValue("SendTo", sendto) if copyto is not None: document.ReplaceItemValue("CopyTo", copyto) if blindcopyto is not None: document.ReplaceItemValue("BlindCopyTo", blindcopyto) # body body = document.CreateRichTextItem("Body") body.AppendText(body_text) # attachment if attach is not None: attachment = document.CreateRichTextItem("Attachment") for att in attach: attachment.EmbedObject(1454, "", att, "Attachment") # save in `Sent` view; default is False document.SaveMessageOnSend = True document.Send(False)
def __init__(self, aspenFile): ''' Parameters file: str, excel file ''' CoInitialize() self.file = aspenFile self.COM = DispatchEx('Apwn.Document') self.COM.InitFromArchive2(self.file)
def convertExcel (fname): pythoncom.CoInitialize() yourExcelFile = fname + '.xlsx' newFileName = fname + '.html' xl = DispatchEx('Excel.Application') wb = xl.Workbooks.Open(yourExcelFile) wb.SaveAs(newFileName, constants.xlHtml) wb.Close(SaveChanges=0) xl.Quit() del xl
def __init__(self, templatefile=None): self.filename = templatefile self.wordApp = DispatchEx('Word.Application') if templatefile == None: self.wordDoc = self.wordApp.Documents.Add() else: self.wordDoc = self.wordApp.Documents.open(templatefile) #set up the selection self.wordDoc.Range(0, 0).Select() self.wordSel = self.wordApp.Selection
def init_emblem(): try: EMB = DispatchEx('Emblem_Modeller4.Application') EMB.Application.AppActivate() except Exception: import os os.system('taskkill /f /im EMBLEM_Modeller4.exe') init_emblem() pass return EMB
def __init__(self, server, file): print('init mail client') self.session = DispatchEx('Notes.NotesSession') self.db = self.session.GetDatabase(server, file) if not self.db.IsOpen: print('open mail db') try: self.db.OPENMAIL except Exception as e: print(str(e)) print('could not open database: {}'.format(db_name))
def __init__(self, server, file): """Initialize @param server Server's name of Notes @param file Your data file, usually ends with '.nsf' """ self.session = DispatchEx('Notes.NotesSession') self.server = self.session.GetEnvironmentString("MailServer", True) self.db = self.session.GetDatabase(server, file) self.db.OPENMAIL self.myviews = []
def setup(self): """ Sets up the initial parameters of the Powerpoint using the Object Model. """ # Enables the following code to be threaded pythoncom.CoInitialize() # @UndefinedVariable # Attempts to generate the Powerpoint using Microsoft's object model try: # Opens the Excel and Powerpoint applications invisibly self.excel = DispatchEx('Excel.Application') self.ppt = DispatchEx('Powerpoint.Application') # Opens up a new Powerpoint presentation self.ppt_file = self.ppt.Presentations.Add(WithWindow=False) # Applies theme self.ppt_file.ApplyTheme(self.ppt_template) except Exception, e: print "Error during setup: %s" % str(e)
def __init__(self, spec=None, add_book=True, xl=None): if spec is not None: warn('spec is ignored on Windows.') if xl is None: # new instance try: self._xl = COMRetryObjectWrapper(DispatchEx('Excel.Application')) except pywintypes.com_error: # for system with WPS Office installed self._xl = COMRetryObjectWrapper(DispatchEx('KET.Application')) if add_book: self._xl.Workbooks.Add() self._hwnd = None elif isinstance(xl, int): self._xl = None self._hwnd = xl else: self._xl = xl self._hwnd = None