Possible to alter worksheet order in xlsxwriter?

2019-04-22 06:54发布

I have a script which creates a number of the following pairs of worksheets in order:

WorkSheet (holds data) -> ChartSheet using WorkSheet

After the script is finished, I am left with worksheets ordered as such:

Data1, Chart1, Data2, Chart2, Data3, Chart3, ...

Is it possible to re-order the worksheets at the end of the script (i.e. before workbook.close()) to obtain the following worksheet order in the final .xlsx file?

Chart1, Chart2, Chart3,...,ChartN, Data1, Data2, Data3,...

2条回答
放荡不羁爱自由
2楼-- · 2019-04-22 07:36

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()
查看更多
狗以群分
3楼-- · 2019-04-22 07:53

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.

查看更多
登录 后发表回答