python对具有宏excel的操作

一、使用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)
posted @ 2019-12-15 00:03  Maple_feng  阅读(3219)  评论(0编辑  收藏  举报