【问题标题】:Move a worksheet in a workbook using openpyxl or xl* or xlsxwriter?使用 openpyxl 或 xl* 或 xlsxwriter 在工作簿中移动工作表?
【发布时间】:2018-06-28 12:04:04
【问题描述】:

我已经阅读了openpyxlxlwtxlrdxlutilsxlsxwriter 的文档。我找不到在 Excel 工作簿 中移动工作表的方法。测试在末尾添加了一个工作表。

具体来说,我有一个类似的日历,['JAN','FEB',...,'DEC'],我需要根据需要更换月份。

如果您不移动 Excel 工作簿中的工作表,如何对其进行排序?您可以在指定的工作表之后之前插入工作表吗?

只有另外一个post I can find on SO 使用win32comBook.Worksheets.Add(After=Sheet);似乎很奇怪,这些模块都没有这种方法。

默认似乎在工作簿末尾添加工作表。我可以复制目标文件,直到到达更新的工作表,插入新工作表,然后将原始副本继续到最后。 (灵感来自this post

【问题讨论】:

    标签: python excel openpyxl xlsxwriter xlwt


    【解决方案1】:

    我有两个问题。第一个问题是在给定位置插入一张纸。第二个问题是移动一张纸。由于我主要处理较新的 Excel 文件 xlsx,所以我将使用 openpyxl。

    各种消息来源表明新工作表已添加到末尾。我预计我每次都需要这样做,然后移动工作表。我问了“(如何)移动工作表......”这个问题,我认为这可以解决这两个问题。

    最终,第一个问题很容易,一旦我终于找到了一个示例,该示例显示workbook.create_sheet() 方法采用可选的index 参数在给定的零索引位置插入新工作表。 (我真的要学会看代码,因为answer was here):

     def create_sheet(self, title=None, index=None):
            """Create a worksheet (at an optional index)
            [...]
    

    接下来。事实证明,您可以通过重新排序工作簿容器_sheets 来移动工作表。所以我做了一个小助手函数来测试这个想法:

    def neworder(shlist, tpos = 3):
        """Takes a list of ints, and inserts the last int, to tpos location (0-index)"""
        lst = []
        lpos = (len(shlist) - 1)
        print("Before:", [x for x in range(len(shlist))])
        # Just a counter
        for x in range(len(shlist)):
            if x > (tpos - 1) and x != tpos:
                lst.append(x-1)
            elif x == tpos:
                lst.append(lpos)
            else:
                lst.append(x)
    
        return lst
    
    # Get the sheets in workbook
    currentorder = wb.sheetnames
    # move the last sheet to location `tpos`
    myorder = neworder(currentorder)
    
    >>>Before: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
    >>>After : [0, 1, 2, 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
    
    # get each object instance from  wb._sheets, and replace
    wb._sheets = [wb._sheets[i] for i in myorder]
    

    一旦我意识到它的作用,第一个答案就在 openpyxl 文档中不难发现。有点惊讶的是,更多的博客没有提到移动床单。

    【讨论】:

      【解决方案2】:

      这是我想出的(使用 openpyxl)

      def move_sheet(wb, from_loc=None, to_loc=None):
          sheets=wb._sheets
      
          # if no from_loc given, assume last sheet
          if from_loc is None:
              from_loc = len(sheets) - 1
      
          #if no to_loc given, assume first
          if to_loc is None:
              to_loc = 0
      
          sheet = sheets.pop(from_loc)
          sheets.insert(to_loc, sheet)
      

      【讨论】:

        【解决方案3】:

        补充xtian 解决方案,可选择将工作表从任何位置向前或向后移动到任何位置。

        from pathlib import Path
        from openpyxl import load_workbook
        
        
        def neworder(file, fpos, tpos):
            """Takes a list of ints, and inserts the fpos (from position) int, to tpos (to position)"""
            wb = load_workbook(filename=file)
            shlist = wb.sheetnames  # get current order sheets in workbook
            lst = []
            lpos = (len(shlist) - 1) # last position
            if lpos >= fpos > tpos >= 0:  # move from a high to low position
                for x in range(lpos+1):
                    if x == tpos:
                        lst.append(fpos)
                    elif tpos < x <= fpos:
                        lst.append(x-1)
                    else:
                        lst.append(x)
            if lpos >= tpos > fpos >= 0:  # move from a low to high position
                for x in range(lpos+1):
                    if x == tpos:
                        lst.append(fpos)
                    elif fpos <= x < tpos:
                        lst.append(x+1)
                    else:
                        lst.append(x)
            wb._sheets = [wb._sheets[i] for i in lst]  # get each object instance from  wb._sheets, and replace
            wb.save(filename=file)
            return
        
        
        filex = Path('C:/file.xlsx')
        neworder(filex, 83, 12)  # move worksheet in 83rd position to 12th position
        

        【讨论】:

          【解决方案4】:

          我的答案是基本移动床单。我在 openpyxl 中使用 move_sheets 函数

          假设您有名为 Sheet 1 : "abc" 和 Sheet 2: "xyz" 的工作表,并且您想将 xyz 从第二个位置移动到第一个位置

          import openpyxl as xl
          wb = xl.load_worksheet("C:\\Users\\Desktop\\testfile.xlsx") #load worksheet using the excel file path, make sure you load the file from correct path
          wb.active = 1 #the sheet index starts from 0 , hence 1 will select the second sheet ie xyz
          wb.move_sheet(wb.active, offset = -1) #this will offset the current active sheet which is xyz be one position to the left which in our case is 1st position
          wb.save(//path where you want to save the file.xlsx)
          

          【讨论】:

            猜你喜欢
            • 2018-08-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-23
            • 2020-05-26
            • 1970-01-01
            相关资源
            最近更新 更多