Python使用COM元件操作Excel
阿新 • • 發佈:2018-12-18
做了小部分修改,比如原文中使用win32com.client.Dispatch,這個是在一個程序中操作Excel,如果正在編輯一個Excel,又在執行這段程式碼,會有一定的影響。
所以我修改成了win32com.client.DispatchEx,這表示重新建立一個程序,並在其中操作Excel,如上情況是不會有影響的。
注意:需要先pip install pywin32
# -*- coding: utf-8 -*- from win32com.client import Dispatch import win32com.client import os import sys def getScriptPath(): return os.path.split(os.path.realpath(__file__))[0] class easyExcel: """A utility to make it easier to get at Excel. Remembering to save the data is your problem, as is error handling. Operates on one workbook at a time.""" def __init__(self, filename=None): #開啟檔案或者新建檔案(如果不存在的話) self.xlApp = win32com.client.DispatchEx('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): #關閉檔案 self.xlBook.Close(SaveChanges=0) self.xlApp.Quit() def getCell(self, sheet, row, col): #獲取單元格的資料 "Get value of one cell" sht = self.xlBook.Worksheets(sheet) return sht.Cells(row, col).Value def setCell(self, sheet, row, col, value): #設定單元格的資料 "set value of one cell" sht = self.xlBook.Worksheets(sheet) sht.Cells(row, col).Value = value def setCellformat(self, sheet, row, col): #設定單元格的資料 "set value of one cell" 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): #獲得一塊區域的資料,返回為一個二維元組 "return a 2d array (i.e. tuple of tuples)" 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): #插入圖片 "Insert a picture in sheet" sht = self.xlBook.Worksheets(sheet) sht.Shapes.AddPicture(pictureName, 1, 1, Left, Top, Width, Height) def cpSheet(self, before): #複製工作表 "copy sheet" 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() #xls.addPicture('Sheet1', PNFILE, 20,20,1000,1000) #xls.cpSheet('Sheet1') xls.setCell('sheet1', 2, 1, 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(getScriptPath() + "\\test.xlsx") xls.close()
感覺儲存的時候有點慢,具體原因不明。