0
点赞
收藏
分享

微信扫一扫

Python对表格中的sheet进行排序【openpyxl】工作技能整理系列

海牙秋天 2022-02-08 阅读 69

第一种方法

from openpyxl import load_workbook

workbook = load_workbook('excel.xlsx')
workbook._sheets = sorted(workbook._sheets)

网上找的,大家可以试试,我这边试了没什么用。

第二种方法

这种方法是本人自己探索出来的方法,其思路主要是将原先的表格中的每一个sheet按照我们想要的顺序依次复制到另一个新的表格中,以此达到排序的目的,不过也因此会产生一个新的表格。

def copy_sheet(wb, wb2, sheetnames):
	sheetnames = wb.sheetnames
    for sheetname in sheetnames:
        print(sheetname)
        sheet = wb[sheetname]
        sheet2 = wb2.create_sheet(sheetname)
        # tab颜色
        sheet2.sheet_properties.tabColor = sheet.sheet_properties.tabColor
        
        # 缩放比例
        sheet2.views.sheetView[0].zoomScale = sheet.views.sheetView[0].zoomScale

        # 开始处理合并单元格形式为“(<CellRange A1:A4>,),替换掉(<CellRange 和 >,)' 找到合并单元格
        wm = list(sheet.merged_cells)
        if len(wm) > 0:
            for i in range(0, len(wm)):
                cell2 = str(wm[i]).replace('(<CellRange ', '').replace('>,)', '')
                sheet2.merge_cells(cell2)

        for i, row in enumerate(sheet.iter_rows()):
            sheet2.row_dimensions[i+1].height = sheet.row_dimensions[i+1].height
            for j, cell in enumerate(row):
                sheet2.column_dimensions[get_column_letter(j+1)].width = sheet.column_dimensions[get_column_letter(j+1)].width
                sheet2.cell(row=i + 1, column=j + 1, value=cell.value)

                # 设置单元格格式
                source_cell = sheet.cell(i+1, j+1)
                target_cell = sheet2.cell(i+1, j+1)
                target_cell.fill = copy.copy(source_cell.fill)
                if source_cell.has_style:
                    target_cell._style = copy.copy(source_cell._style)
                    target_cell.font = copy.copy(source_cell.font)
                    target_cell.border = copy.copy(source_cell.border)
                    target_cell.fill = copy.copy(source_cell.fill)
                    target_cell.number_format = copy.copy(source_cell.number_format)
                    target_cell.protection = copy.copy(source_cell.protection)
                    target_cell.alignment = copy.copy(source_cell.alignment)

其中sheetnames为你想要的sheet顺序list。

缺点:如果sheet太多或者内容量太多运行时间就会过长。

结束语

看完这篇,还有更多知识点分享给你哦,自己慢慢找哈,就在下面链接。


推荐关注的专栏

👨‍👩‍👦‍👦 机器学习:分享机器学习实战项目和常用模型讲解
👨‍👩‍👦‍👦 数据分析:分享数据分析实战项目和常用技能整理

往期内容回顾

💚 学习Python全套代码【超详细】Python入门、核心语法、数据结构、Python进阶【致那个想学好Python的你】
❤️ 学习pandas全套代码【超详细】数据查看、输入输出、选取、集成、清洗、转换、重塑、数学和统计方法、排序
💙 学习pandas全套代码【超详细】分箱操作、分组聚合、时间序列、数据可视化
💜 学习NumPy全套代码【超详细】基本操作、数据类型、数组运算、复制和试图、索引、切片和迭代、形状操作、通用函数、线性代数


关注我,了解更多相关知识!

CSDN@报告,今天也有好好学习

举报

相关推荐

0 条评论