【Python】按升序排列 Excel 工作表

发现按名称对 Excel 工作表进行排序很麻烦,因此创建了一个代码来使用 Python 的 openpyxl 对它们进行排序。

1. 本次创建的代码概述

  • 在GUI中指定一个Excel文件(使用Tkinter。这是一个标准模块,因此不需要安装)
  • 加载Excel文件(使用openpyxl,由于它不是标准模块,如果没有安装,需要运行pip install openpyxl)
  • 获取Excel工作表的名称并将其按升序存储在列表中
  • 将工作表排列在 Excel 工作表的末尾(并指定字体)
  • 将 Excel 工作簿单独保存为sorted_<book_name>.xlsx

2. 实际代码

python 复制代码
import os
from tkinter import Tk
from tkinter import filedialog
from openpyxl import load_workbook
from openpyxl.styles.fonts import Font

current_directory = os.path.dirname(__file__)

# Tkinter 配置
root = Tk()
root.geometry("0x0") # window大小为 0
root.overrideredirect(1) # window删除标题栏
file_types = (
    ("excel file", "*.xlsx"),
)

# 所选文件的绝对路径
selected_file = filedialog.askopenfilename(initialdir=current_directory, filetypes=file_types)

# 所选文件的名称
file_name = os.path.basename(selected_file)

# Excel 工作表字体
font = Font(name="Yu Gothic", size=12)

# 加载 Excel 文件
wb = load_workbook(selected_file)

# Excel工作表列表(升序)
ws_title_list = sorted([ws.title for ws in wb.worksheets])
ws_length = len(ws_title_list) - 1

# 执行 Excel 工作表排序
for ws_title in ws_title_list:
    ws = wb[ws_title]

    for row in range(ws.max_row):
        if ws.max_row != 1:
            for col in range(ws.max_column):
                ws.cell(row=row+1, column=col+1).font = font

    wb.move_sheet(ws, offset=ws_length)

wb.save(selected_file.replace(file_name, f"sorted_{file_name}"))

三、总结

创建这段代码是因为每次都按升序排列工作表很麻烦。 由于快速创建了它,所以无法弄清楚想要对哪些工作表进行排序,哪些工作表不需要(例如,不对某些工作表进行排序),所以正在考虑将其作为下一个挑战。

相关推荐
A懿轩A5 小时前
Ghostty:告别 Mac 毛坯终端,打造 2026 最丝滑的 Ghostty AI 开发驾驶舱——Claude Code 团队也在用
python·macos·策略模式
Chasing Aurora5 小时前
python 安装依赖和导入模块 详解
开发语言·python·虚拟环境·import·pyenv·requirements
念恒123065 小时前
Python(for循环)
python·学习
咱那飘逸的长发5 小时前
Trae java项目配置全局maven和jdk
java·python·maven
码界筑梦坊5 小时前
116-基于Flask的健身房会员锻炼数据可视化分析系统
python·信息可视化·数据分析·flask·毕业设计
wcy_10115 小时前
QCoder智能生成Excel数据清洗与可视化代码
python·excel
财经资讯数据_灵砚智能6 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月2日
人工智能·python·信息可视化·自然语言处理·ai编程
skiy6 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
2601_956139426 小时前
集团品牌全案公司哪家专业
大数据·人工智能·python
ouliten6 小时前
[Triton笔记1]核心概念
笔记·python·深度学习·triton