zoukankan      html  css  js  c++  java
  • python-win32操作excel的一些特殊功能

    一、代码

    特殊操作包括(隐藏列,解锁工作表保护,插入批注,创建文本框,追加修改单元格内容)

    from openpyxl import load_workbook
    import win32com.client
    
    # 隐藏列
    def hidden_column(path, column, sheet_name=0):
        '''
        :param path: 文件路径
        :param column: 列名,如A,B,C,可以传入单个,可以是区间[B,E]
        :return:
        '''
        try:
            wb = load_workbook(path, data_only=True)
            if isinstance(sheet_name, str):
                ws = wb.get_sheet_by_name(sheet_name)
            else:
                ws = wb.worksheets[sheet_name]
            if isinstance(column, list):
                ws.column_dimensions.group(column[0], column[1], hidden=True)
            else:
                ws.column_dimensions[column].hidden = True
            wb.save(path)
        except Exception as e:
            print("打开文件失败:%s" % e)
    
    # 解锁工作表保护
    def unlock_excel(path, password, sheet_name="Sheet1"):
        '''
        :param path: 文件路径
        :param password:工作表保护密码
        :param sheetname: sheet名
        :return:
        '''
        xlApp = win32com.client.DispatchEx("Excel.Application")
        try:
            # 后台运行, 不显示, 不警告
            xlApp.Visible = False
            xlApp.DisplayAlerts = False
            wb = xlApp.Workbooks.Open(path)
            # 屏蔽弹窗
            wb.Checkcompatibility = False
            sht = wb.Worksheets(sheet_name)
            sht.Unprotect(password)
            wb.Save()
            wb.Close(SaveChanges=True)
        except Exception as e:
            xlApp.Quit()
            print("打开文件失败:%s" % e)
    
    # 插入批注
    def insert_notes(path, cell, content, sheet_name="Sheet1"):
        '''
        :param path: 文件路径
        :param cell: 批注单元格:如B4
        :param content: 批注内容
        :param notes_name: 批注人名
        :param sheet_name: sheet名
        :return:
        '''
        xlApp = win32com.client.DispatchEx("Excel.Application")
        try:
            # 后台运行, 不显示, 不警告
            xlApp.Visible = False
            xlApp.DisplayAlerts = False
            wb = xlApp.Workbooks.Open(path)
            sht = wb.Worksheets(sheet_name)
            if not sht.Range(cell).Comment:
                sht.Range(cell).AddComment()
            sht.Range(cell).Comment.Text(content)
            wb.Save()
            wb.Close()
        except Exception as e:
            xlApp.Quit()
            print("打开文件失败:%s" % e)
    
    # 创建文本框
    def create_text_box(path, left,top,Width,Height,content, sheet_name="Sheet1"):
        xlApp = win32com.client.DispatchEx("Excel.Application")
        try:
            # 后台运行, 不显示, 不警告
            xlApp.Visible = False
            xlApp.DisplayAlerts = False
            wb = xlApp.Workbooks.Open(path)
            sht = wb.Worksheets(sheet_name)
            # 分别是文字方向,文本框的左上角相对于文档左上角的位置,
            # 相对于文档顶部的文本框左上角的位置,文本框的宽度,文本框的高度(以磅为单位)
            # 磅的大小为 1/72 英寸。 字号通常用磅衡量
            sht.Shapes.AddTextbox(1, left,top,Width,Height).TextFrame.Characters().Text=content
            wb.Save()
            wb.Close()
        except Exception as e:
            xlApp.Quit()
            print("打开文件失败:%s" % e)
    
    
    # 读取单元格,并修改单元格
    def add_content_cell(path,cell,add_content,sheet_name="Sheet1"):
        xlApp = win32com.client.DispatchEx("Excel.Application")
        try:
            # 后台运行, 不显示, 不警告
            xlApp.Visible = False
            xlApp.DisplayAlerts = False
            wb = xlApp.Workbooks.Open(path)
            sht = wb.Worksheets(sheet_name)
            value=sht.Range(cell).Value
            sht.Range(cell).Value=value.strip("
    ")+"
    "+add_content
            wb.Save()
            wb.Close()
        except Exception as e:
            xlApp.Quit()
            print("打开文件失败:%s" % e)

    二、对win32进行了open,close封装

    class Win32_excel(object):
        def __init__(self, path, sheet_name="Sheet1"):
            self.xlApp = win32com.client.DispatchEx("Excel.Application")
            self.path = path
            self.sheet_name = sheet_name
    
        def __enter__(self):
            try:
                # 后台运行, 不显示, 不警告
                self.xlApp.Visible = False
                self.xlApp.DisplayAlerts = False
                self.wb = self.xlApp.Workbooks.Open(self.path)
                # 屏蔽弹窗
                self.wb.Checkcompatibility = False
                self.sht = self.wb.Worksheets(self.sheet_name)
                return self
            except Exception as e:
    self.xlApp.Quit()
    print("打开文件失败:%s" % e) def __exit__(self, exc_type, exc_val, exc_tb): self.wb.Save() self.wb.Close(SaveChanges=True) self.xlApp.Quit() # 解锁工作表保护 def unlock_excel(self, password): self.sht.Unprotect(password) # 插入批注 def insert_notes(self, cell, content): if not self.sht.Range(cell).Comment: self.sht.Range(cell).AddComment() self.sht.Range(cell).Comment.Text(content) # 创建文本框 def create_text_box(self, left, top, Width, Height, content): # 分别是文字方向,文本框的左上角相对于文档左上角的位置, # 相对于文档顶部的文本框左上角的位置,文本框的宽度,文本框的高度(以磅为单位) # 磅的大小为 1/72 英寸。 字号通常用磅衡量 self.sht.Shapes.AddTextbox(1, left, top, Width, Height).TextFrame.Characters().Text = content # 读取单元格,并修改单元格 def add_content_cell(self, cell, add_content): value = self.sht.Range(cell).Value self.sht.Range(cell).Value = value.strip(" ") + " " + add_content # 复制单元格 def copy_cells(self, copy_cells, to_cells): # copy_cells,如:"A1:B1" # to_cells,如:"A2:B2" self.sht.Range(copy_cells).Copy() self.sht.Range(to_cells).PasteSpecial() # 插入单元格 def insert_cells(self,cells): # cells,如:"A1:E1" self.sht.Range(cells).Insert() # 插入行 def insert_row(self,row): # 在第几行之前插入新行 self.sht.Rows(row).Insert() # 单元格写入 def write(self,cell,content): self.sht.Range(cell).Value=content if __name__ == '__main__': path=r"日报.xlsx" df=pd.read_excel(path,sheet_name="sheet名") row=df.shape[0] print(row) with Win32_excel(path,sheet_name="sheet名") as w32: w32.insert_row(row+1) w32.copy_cells("A%s:G%s"%(row,row),"A%s:G%s"%(row+1,row+1))
  • 相关阅读:
    451. Sort Characters By Frequency
    424. Longest Repeating Character Replacement
    68. Text Justification
    44. Wildcard Matching
    160. Intersection of Two Linked Lists
    24. Swap Nodes in Pairs
    93. 递归实现组合型枚举
    98. 分形之城
    97. 约数之和
    96. 奇怪的汉诺塔
  • 原文地址:https://www.cnblogs.com/angelyan/p/13094204.html
Copyright © 2011-2022 走看看