Xlsxwriter and Excel “=Sort()” Function?

I learned in this SO post about using XLSXWriter to add a =FILTER() function to a workbook.

Now I'm trying to add a =SORT() function. So far I have tried this:

worksheet.write_array_formula('H2', '=_xlfn._xlws.SORT(A2:F16, 6, -1)')

...but SORT doesn't appear to be an array formula. I have also tried this:

worksheet.write_formula('H2', '=_xlfn.SORT(A2:F16, 6, -1)')

worksheet.write_formula('H2', '=_xlfn._xlws.SORT(A2:F16, 6, -1)')

The formula appears in the worksheet, but instead of being:

=SORT(A2:F16, 6, -1)

...it appears as:

=@SORT(A2:F16, 6, -1)

How can I correct this?

1 Answer

This is similar to the other answer that you linked to and your first attempt is almost correct. I think you just need to specify a range that the range formula applies to like this:

import xlsxwriter

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

worksheet.write_array_formula('H2:M16', 
                              '=_xlfn._xlws.SORT(A2:F16, 6, -1)')

workbook.close()

Output:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest