Possible to alter worksheet order in xlsxwriter?

You can create dummy sheets in the order you want and them fill them up with real data in any order:

import pandas as pd
dummy = pd.DataFrame()
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
# Here go the dummy sheets in the order you want
dummy.to_excel(writer, sheet_name='Chart1')
dummy.to_excel(writer, sheet_name='Chart2')
dummy.to_excel(writer, sheet_name='Data1')
dummy.to_excel(writer, sheet_name='Data2')
# Then you fill-in the placeholders in whatever order:
data1.to_excel(writer, sheet_name='Data1')
chart1.to_excel(writer, sheet_name='Chart1')
data2.to_excel(writer, sheet_name='Data2')
chart2.to_excel(writer, sheet_name='Chart2')
writer.close()

I'm the author of XlsxWriter. It is possible to do it but it isn't advisable.

Each worksheet has an internal index which is used by Excel to track the relationship of different workbook objects.

Sorting the worksheets might work in some simple cases but for more complex workbooks it could lead to problems.


Just sort workbook.worksheets_objs list:

import xlsxwriter


workbook = xlsxwriter.Workbook('test.xlsx')

sheet_names = ['Data1', 'Chart1', 'Data2', 'Chart2', 'Data3', 'Chart3']
for sheet_name in sheet_names:
    workbook.add_worksheet(sheet_name)

# sort sheets based on name
workbook.worksheets_objs.sort(key=lambda x: x.name)
workbook.close()