【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}"))

三、总结

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

相关推荐
勇往直前plus22 分钟前
从文件到屏幕:Python/java 字符编码、解码、文本处理的底层逻辑解析
java·开发语言·python
~央千澈~28 分钟前
优雅草科技2026年2月重磅产品·优雅草·写作中枢 — 产品介绍与发布说明
python
Emotional。4 小时前
2025 年度技术总结与规划:AI 时代的开发者成长之路
人工智能·python·ai·langchain
witAI8 小时前
**AI仿真人剧制作软件2025推荐,解锁沉浸式数字内容创作
人工智能·python
Codefengfeng9 小时前
Python Base环境中加包的方法
开发语言·python
清水白石0089 小时前
《Python 编程全景解析:从核心精要到测试替身(Test Doubles)五大武器的实战淬炼》
开发语言·python
如若12310 小时前
AutoDL云服务器 NVIDIA 570驱动 EGL渲染修复全记录
运维·服务器·python
甲枫叶10 小时前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
清水白石00811 小时前
《Python 编程全景解析:从核心精要到 Hypothesis 属性基测试的边界探索》
开发语言·python
勇往直前plus11 小时前
深入理解 Python 内存模型:模块、类、对象的存储与运行机制
开发语言·python