如何用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_orderlist 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 usecustom_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
相关产品推荐
相关产品推荐

