You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用xlsxwriter实现Excel工作表自定义排序(非名称排序)

Custom Worksheet Ordering with XlsxWriter

To reorder your Excel worksheets in your desired custom sequence instead of alphabetical order, you just need to adjust the sorting key to reference your predefined order list. Here's the modified code:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
sheet_names = ['Data1', 'Chart1', 'Data2', 'Chart2', 'Data3', 'Chart3']

# Add all worksheets to the workbook
for sheet_name in sheet_names:
    workbook.add_worksheet(sheet_name)

# Define your custom worksheet order
custom_order = ['Data1', 'Chart1', 'Chart3', 'Chart2', 'Data3', 'Data2']

# Sort worksheets using the custom order (by their index in the custom list)
workbook.worksheets_objs.sort(key=lambda x: custom_order.index(x.name))

workbook.close()

How it works:

  • We first define your custom_order list which specifies the exact sequence you want your worksheets to appear in.
  • When sorting workbook.worksheets_objs, instead of using the sheet name as the key, we use custom_order.index(x.name) which returns the position of each sheet name in your custom list. This ensures the worksheets are sorted to match your predefined sequence perfectly.

Note:

Make sure every sheet name you add to the workbook is included in the custom_order list. If a sheet name is missing, this will throw a ValueError—but since your custom list already includes all the sheets from your original sheet_names list, you're good to go!

内容的提问来源于stack exchange,提问作者Martin Bouhier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:52:04