win32com模块
生活随笔
收集整理的這篇文章主要介紹了
win32com模块
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import win32com.client as win32
建立一個可視的excel
app = 'Excel' xl = win32.gencache.EnsureDispatch('%s.Application' % app) ss = xl.Workbooks.Add() sh = ss.ActiveSheet """ 0代表隱藏對象,但可以通過菜單再顯示 -1代表顯示對象 2代表隱藏對象,但不可以通過菜單顯示,只能通過VBA修改為顯示狀態(tài)"""xl.Visible = True編輯excel
sh.Cells(1,1).Value =1 #A1賦值為1 sh.Cells(1,1).Font.Bold = True #加粗 sh.Range(sh.Cells(1, 1),sh.Cells(1,5)).Font.Name = "Times New Roman"#選擇指定區(qū)域 sh.Range(sh.Cells(1, 1), sh.Cells(1,5)).Font.Size = 10.5 sh.Cells(row, col).Name = "Arial"#字體類型 sh.Rows(row).Delete()#刪除行 sh.Columns(row).Delete()#刪除列sh.Range(sh.Cells(1,1),sh.Cells(1,1)).HorizontalAlignment = win32.constants.xlCenter #水平居中xlCentersh.SaveAs(path+'demo.xls') ss.Close(False) xl.Application.Quit() from win32com.client import Dispatch import win32com.client class easyExcel: def __init__(self, filename=None): #打開文件或者新建文件(如果不存在的話) self.xlApp = win32com.client.Dispatch('Excel.Application') if filename: self.filename = filename self.xlBook = self.xlApp.Workbooks.Open(filename) else: self.xlBook = self.xlApp.Workbooks.Add() self.filename = '' def save(self, newfilename=None): #保存文件 if newfilename: self.filename = newfilename self.xlBook.SaveAs(newfilename) else: self.xlBook.Save() def close(self): #關(guān)閉文件 self.xlBook.Close(SaveChanges=0) del self.xlApp def getCell(self, sheet, row, col): #獲取單元格的數(shù)據(jù) sht = self.xlBook.Worksheets(sheet) return sht.Cells(row, col).Value def setCell(self, sheet, row, col, value): #設(shè)置單元格的數(shù)據(jù) sht = self.xlBook.Worksheets(sheet) sht.Cells(row, col).Value = value def setCellformat(self, sheet, row, col): #設(shè)置單元格的數(shù)據(jù)樣式sht = self.xlBook.Worksheets(sheet) sht.Cells(row, col).Font.Size = 15#字體大小 sht.Cells(row, col).Font.Bold = True#是否黑體 sht.Cells(row, col).Name = "Arial"#字體類型 sht.Cells(row, col).Interior.ColorIndex = 3#表格背景 #sht.Range("A1").Borders.LineStyle = xlDouble sht.Cells(row, col).BorderAround(1,4)#表格邊框 sht.Rows(3).RowHeight = 30#行高 sht.Cells(row, col).HorizontalAlignment = -4131 #水平居中xlCenter sht.Cells(row, col).VerticalAlignment = -4160 # def deleteRow(self, sheet, row): sht = self.xlBook.Worksheets(sheet) sht.Rows(row).Delete()#刪除行 sht.Columns(row).Delete()#刪除列def getRange(self, sheet, row1, col1, row2, col2): #獲得一塊區(qū)域的數(shù)據(jù),返回為一個二維元組 sht = self.xlBook.Worksheets(sheet) return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value def addPicture(self, sheet, pictureName, Left, Top, Width, Height): #插入圖片 sht = self.xlBook.Worksheets(sheet) sht.Shapes.AddPicture(pictureName, 1, 1, Left, Top, Width, Height) def cpSheet(self, before): #復(fù)制工作表 shts = self.xlBook.Worksheets shts(1).Copy(None,shts(1))def inserRow(self,sheet,row): #插入一個工作表sht = self.xlBook.Worksheets(sheet)sht.Rows(row).Insert(1)#下面是一些測試代碼。 if __name__ == "__main__": #PNFILE = r'c:/screenshot.bmp' xls = easyExcel(r'd:\jason.li\Desktop\empty_book.xlsx') #xls.addPicture('Sheet1', PNFILE, 20,20,1000,1000) #xls.cpSheet('Sheet1') xls.setCell('sheet1',2,'A',88) row=1 col=1 print("*******beginsetCellformat********") # while(row<5):# while(col<5):# xls.setCellformat('sheet1',row,col)# col += 1# print("row=%s,col=%s" %(row,col))# row += 1# col=1# print("*******row********")# print("*******endsetCellformat********")# print("*******deleteRow********")# xls.deleteRow('sheet1',5)xls.inserRow('sheet1',7)xls.save() xls.close() from win32com.client import Dispatch import win32com.client import time# 獲取excel 對象excel = win32com.client.Dispatch('Excel.Application')""" 0代表隱藏對象,但可以通過菜單再顯示 -1代表顯示對象 2代表隱藏對象,但不可以通過菜單顯示,只能通過VBA修改為顯示狀態(tài) """ excel.Visible = -1# 打開excelmyBook = excel.Workbooks.Open("e:/接口測試用例.xlsx")# sheet頁,可以是序號,也可以是名稱 mySheet = myBook.Worksheets("過程結(jié)果") #excel的下標(biāo)都是從1開始的 #mySheet = myBook.Worksheets(1)time.sleep(2)# 刪除行,清除歷史數(shù)據(jù) mySheet.Rows("2:500").delete #mySheet.Columns("1").delete# 獲取當(dāng)前sheet頁有效的行數(shù) LastRow = mySheet.usedrange.rows.count print("該sheet頁目前已經(jīng)存在", LastRow, "行")# 獲取當(dāng)前sheet頁有效的列數(shù) LastColumn = mySheet.usedrange.columns.count print(LastColumn)# 焦點轉(zhuǎn)移到sheet頁 mySheet.Activate # 給單元格賦值 Cells(行,列) mySheet.Cells(2, 2).Value = "使用win32com" # 設(shè)置單元格字體位紅色 mySheet.Cells(2, 2).Font.Color = -16776961 # 設(shè)置單元格字體為粗體 mySheet.Cells(2, 2).Font.Bold = True # 設(shè)置單元格字體 mySheet.Cells(2, 2).Font.Name = "微軟雅黑"time.sleep(1)mySheet.Activate mySheet.Cells(2, 3).Value = "使用win32com" # 設(shè)置單元格字體位綠色 mySheet.Cells(2, 3).Font.Color = -11489280 mySheet.Cells(2, 3).Font.Bold = True# 獲取一個單元格的值 aCellValue=mySheet.Cells(2, 3).Value print(aCellValue)# 獲取一個范圍的值,類型為嵌套的list range_list=mySheet.Range(mySheet.Cells(1, 1), mySheet.Cells(5, 5)).Value# 給一個范圍賦值,輸入的值應(yīng)該為嵌套的list mySheet.Range(mySheet.Cells(6, 1), mySheet.Cells(10, 10)).Value = range_list # 改變一個范圍的屬性值 mySheet.Range(mySheet.Cells(6, 1), mySheet.Cells(10, 10)).Font.Color = -11489280# 如果范圍是一行的話,賦值應(yīng)該使用非嵌套的list,例如: row_v=(1,2,3,4) mySheet.Range(mySheet.Cells(11, 1), mySheet.Cells(11, 4)).Value = row_v# 給整個一行賦值,慎用。。。 mySheet.Rows(12).Value = row_v print(range_list)#單元格添加顏色 WinSheet.Cells(1, 1).Interior.ColorIndex = 3 #或者Range("A1") WinSheet.Range("A1").Interior.ColorIndex = 3 #3=紅色,不同的值代表不同的顏色,可以去查看msdn vba 文檔,這就不詳細(xì)說了#再是RGB調(diào)色方式#Cells 和 Range都可以,Range可以選擇一大片區(qū)域 WinSheet.Cells(1, 1).Interior.Color = RGB(0, 0, 255) #或 WinSheet.Range("A1").Interior.Color = RGB(255, 0, 255) #字體的顏色也是一樣 WinSheet.Cells(1, 1).Font.ColorIndex = 3 WinSheet.Cells(1, 1).Font.Color = RGB(0, 0, 255)# 保存 myBook.save# 退出 myBook.close import win32com.client as win32# add_a_workbook excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True """0代表隱藏對象,但可以通過菜單再顯示-1代表顯示對象2代表隱藏對象,但不可以通過菜單顯示,只能通過VBA修改為顯示狀態(tài) """ excel.Application.ScreenUpdating = False # 關(guān)閉屏幕更新 excel.DisplayAlerts = 0 # 不警告wb = excel.Workbooks.Add() # 新建工作薄 # wb = excel.Workbooks.Open('workbook1.xlsx')# 打開已存在的工作薄 wb.SaveAs('add_a_workbook.xlsx') # 新建的用SaveAa(),否則用Save() # wb.Close(SaveChanges=0) excel.Application.Quit()# add_a_worksheet sht = wb.Worksheets.Add() # wb.Worksheets("Sheet1") # 已存在 # wb.Worksheets(1) # 序號 sht.Name = 'sheet1' sht.Range("A1").Value = 1# Range and Offset sht.Cells(1,1).Value = 'A1' # 從1開始sht.Cells(1,1).Offset(2,4).Value = "D2" # ?# offset中的參數(shù)自身就算一行一列,這是與VBA不同處sht.Range("A2").Value = 'A2' sht.Range("A3:B4").Value = 'A3:B4' sht.Range("A6:B7,A9:B10").Value = "A6:B7,A9:B10" sht.Range(sht.Cells(1,1),sht.Cells(3,3)).Value = rglist # 嵌套的列表# cell_color and Format for i in range (1,21):sht.Cells(i,1).Value = isht.Cells(i,1).Interior.ColorIndex = isht.Cells(3,2).Font.Color = -16776961sht.Cells(3,2).Font.Bold = True sht.Cells(3,2).Font.Name = '宋體'sht.Range("A1:A5").HorizontalAlignment = win32.constants.xlRight# 返回或設(shè)置指定對象的水平對齊方式 靠右 sht.Rows(1).VerticalAlignment = win32.constants.xlCenter# 返回或設(shè)置指定對象的垂直對齊方式 居中sht.Rows.AutoFit() # 可自動調(diào)整工作表中的所有行 sht.Range("B1:B5").NumberFormat = "$###,##0.00" # autoFill sht.Range("A1:A2").AutoFill(sht.Range("a1:a10"),win32.constants.xlFillDefault)# 將A1:A2自動填充到A1:A10# Column/Row Formatting sht.Columns(1).ColumnWidth = 1 sht.Range("B:B").ColumnWidth = 1sht.Columns.AutoFit() # 可自動調(diào)整工作表中的所有列sht.Rows("2:500").Deletesht.Rows(12).Value = '' # 整行 sht.Range('E2').EntireColumn.Address # $E:$E 整列 sht.Range('E2').EntireRow.Address # $2:$2 整行# UsedRange row = len(sht.UsedRange.Rows) # 已使用的最大區(qū)域的行數(shù)# sht.UsedRange.Rows.Count # 拋異常 無此屬性sht.UsedRange.Rows(1).Value[0] sht.UsedRange.Rows.Value sht.UsedRange.Address sht.UsedRange.Cells(1).Address # 絕對地址 sht.UsedRange.Cells(1).Row # 已用區(qū)域的起始點行號# CurrentRegion sht.Range('E2').CurrentRegion.Count # UsedRange中無此屬性# 區(qū)域中所有單元格總數(shù) sht.Range('E2').CurrentRegion.Rows.Count# 區(qū)域中行數(shù)和# Intersect # (同工作表中的)參數(shù)的重疊區(qū)域 excel.Application.Intersect(sht.Range('a2:b3'),sht.Range('b3:c4')).Address# $B$3# End sht.Cells(2,1).End(win32.constants.xlDown).Offset(2,1).Value = '' sht.Rows(2).End(win32.constants.xlToRight).Address# 函數(shù)意義及方向同VBA: xlToLeft/ xlUp / xlToRight/ xlDown# Resize # ? sht.Range('E2').Resize(2,2).Address # $F$3 sht.Range('E2').Offset(2,2).Address # $F$3# Resize并未擴大區(qū)域,效果與Offset效果,為何?(在wps中測試) # Activate/Select 焦點轉(zhuǎn)移 sht.Activate sht.Select() excel.Selection.ColumnWidth = 4 # 只能是excel !!# Names wb.Names.Count # sht.Names.Count 下同 wb.Names(1).Name wb.Names(1).Visible = False # 隱藏 sht.Names(1).Name = 'date' # 重命名sht.Range('A2').Name = 'STD' print(sht.Range('STD').Value) print(sht.Evaluate('STD')) # 同上一行wb.Names.Add(Name="abc",RefersTo="=sheet1!$A$1:$J$1",Visible=False)# 創(chuàng)建新的命名# RefersTo中不加工作表名時為全局命名(整個工作簿可用),否則為局部命名 sht.Names.Add("abc","=$A$1:$J$1",True) # 創(chuàng)建sht中的局部命名print(help(sht.Names.Add)) # 查看Add函數(shù)有哪些參數(shù)# Copying Data from Worksheet to Worksheetsht.Range('A2:J10').Formula = "=row()*column()" # 公式wb.Worksheets.FillAcrossSheets(wb.Worksheets("Sheet1").Range("A2:J10")) # 將sheet1中A2:J10的數(shù)據(jù)復(fù)制到wb中所有工作表的相同位置# FillAcrossSheets:將單元格區(qū)域復(fù)制到集合中所有其他工作表的同一位置# 還有一可選參數(shù),指定如何復(fù)制區(qū)域:# xlFillWithAlldefault/xlFillWithContents/xlFillWithFormats(詳VBA)sht.Copy(None,sht) # 參數(shù):Copy(Before,After) # 復(fù)制工作表 sht.UsedRange.Rows(1).Copy(sht.Range('F2')# 將已用區(qū)域的第一行數(shù)據(jù)復(fù)制到從F2開始的單元格區(qū)域(自動擴展)sht.Range("B2:K2").Value = [i for i in range(1,11)]# 同一行賦值func = excel.Application.WorksheetFunction.Transpose# VBA中的轉(zhuǎn)置函數(shù)sht.Range("B2:B11").Value = list(zip([i for i in range(1,11)]))# 同一列賦值 變?yōu)槎嘈幸涣?/span> sht.Range("B2:B11").Value = func([i for i in range(1,11)])# 同上sht.Range('f1:h1').Value = func(sht.Range('b3:b5').Value)# 同一行賦值 將列中的值倒置sht.Range("B2:E4").Value = sht.Range("B6:E8").Value# 多維 對 多維# FormatConditions: 條件格式 參見VBAsht.Range("B2:K33").Select() excel.Selection.FormatConditions.AddColorScale(ColorScaleType = 3)# 添加三色度漸變刻度 二色度參數(shù)為2rng = sht.UsedRange CON = win32.constants rng.FormatConditions.Add(CON.xlCellValue,CON.xlEqual,'A') # 值 等于A# sht/wb 無FormatConditions屬性 rng.FormatConditions(rng.FormatConditions.Count).Interior.ColorIndex = 3# 給前面新建的添加格式 前面新建的在最末或: fmt = rng.FormatConditions.Add(CON.xlCellValue,CON.xlEqual,'A') fmt.Interior.ColorIndex = 3 fmt.Border # 拋異常 excel.Selection.FormatConditions(excel.Selection.FormatConditions.Count).SetFirstPriority()[csc1,csc2,csc3] = [excel.Selection.FormatConditions(1).ColorScaleCriteria(n) for n in range(1,4)] csc1.Type = win32.constants.xlConditionValueLowestValue csc1.FormatColor.Color = 13011546 csc1.FormatColor.TintAndShade = 0# AddComment 添加批注 sht.Cells(1).AddComment("abc") # 同一地址不能重復(fù)添加 sht.Cells(1).Comment.Visible = True # 批注顯示或隱藏 sht.Cells(1).Comment.Text('ppp') # 更改批注內(nèi)容 sht.Cells(1).Comment.Delete() # 刪除# AutoFilter 自動篩選 sht.AutoFilterMode = False # 去掉原來的篩選 sht.UsedRange.Columns(5).AutoFilter(1,"=C")# 參見VBA# FileDialog 文件對話框--->返完整路徑 fdag = excel.Application.FileDialog(3) # 參數(shù): 3:文件選擇 設(shè)置后可多選4:文件夾選擇1:文件打開 fdag.AllowMultiselect= True # 多選設(shè)置 文件夾時無效 if fdag.show == -1: # 對話框點"確定"時返-1print(list(fdag.SelectedItems)) # 選擇結(jié)果# PageSetup 頁面設(shè)置 pgs = sht.PageSetup pgs.Zoom = 150 # 縮放比例 10--400% 之間 pgs.PrintArea = sht.UsedRange.Address # 打印區(qū)域 pgs.Orientation = win32.constants.xlLandscape # 橫向打印 縱向為:xlPortrait sht.PrintPreview(True) # 打印預(yù)覽將工作表轉(zhuǎn)化為JSON
import _wh_lib as wh import jsonwps = win32.gencache.EnsureDispatch('Excel.Application') wps.Visible = Truewb = wps.Workbooks.Open('D:\ABC分析.xls') sht = wb.Worksheets(1) rows = sht.UsedRange.Rowsres = list() json.encoder.FLOAT_REPR = lambda x:format(x,'.4f') # 設(shè)置小數(shù)位 with wh.TimeTest():#--------------------------keys = rows(2).Value[0] # 列表元素為字典的key# rows的參數(shù)從1開始for i in range(3,len(rows)):res.append(OrderedDict(zip(keys,rows(i).Value[0])))s = json.dumps(res,indent=4,ensure_ascii=False)print(s) # -------下面的算法快得多-----# vals = sht.UsedRange.Rows.Value # 一次獲取全部值# keys = vals[1] # 列表從0開始計數(shù)# for row in range(2,len(vals)): # res.append(OrderedDict(zip(keys,vals[row])))# s = json.dumps(res,indent=4,ensure_ascii=False)# print(s)總結(jié)
以上是生活随笔為你收集整理的win32com模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于Linux的虚拟主机搭建
- 下一篇: druid.io 海量实时OLAP数据仓