一、使用win32com庫
安裝pip install pypiwin32 import win32com.client #excel xlApp =win32com.client.DispatchEx("Excel.Application") #后台運行, 不顯示, 不警告 xlApp.Visible = 0 xlApp.DisplayAlerts = 0 FileName = r"C:\Users\ffm11\Desktop\mydata.xls" # excel xlBook = xlApp.Workbooks.Open(FileName) # 屏蔽彈窗 xlBook.Checkcompatibility = False try: #獲取sheet _sheet = xlBook.Worksheets('Sheet1') _sheet2 = xlBook.Worksheets('Sheet2') # 獲取指定單元格 print(_sheet.Cells(1,1).Value) # 打印機 # _sheet.PrintOut()
# 取消篩選
_sheet.AutoFilterMode = False # 循環獲取所有cell單元格 datatupe = _sheet.UsedRange.Value print(datatupe) # 把所有單元格設置為空 _sheet.UsedRange.Value="" # 賦值sheet內容 _sheet.UsedRange.Value = _sheet2.UsedRange.Value #excel # xlBook.SaveAs(FileName)#另存為 xlBook.Save() except Exception as e: print(e) finally: #excel xlBook.Close() xlApp.Quit()
二、工作表加密解密
import win32com.client FilePath=r"*****" excel = win32com.client.Dispatch('Excel.Application') wb = excel.Workbooks.Open(FilePath) excel.Visible = False sht=wb.Worksheets("Sheet1") # sht.Unprotect("1234") #解除鎖定 sht.Protect() #增加鎖定 wb.Save() wb.Close(SaveChanges=True)
