Search code examples
pythonexport-to-excelxlwt

Export to excel with python and xlwt using condition in column number


I make an export of a list to excel with Python (xlwt):

response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=MyList.xls'

wb = xlwt.Workbook()
ws = wb.add_sheet('my_list')

ws.write(0, 0, 'Country ID')
if var =='with_flag':
    ws.write(0, X, 'Country Flag')
ws.write(0, 1, 'Country Name')

If I export without flag the export passed nickel ;) , but the problem is when I choose to export with flag. I should respect the order of columns (1- country_name, 2- country_flag , 3-country_id). I know that Python doesn't support ++. Is there any condition to make on X in my code to have the export in the specific order ?


Solution

  • If I understand your question right, you want something like this:

    X = 1
    if var =='with_flag':
        ws.write(0, X, 'Country Flag')
        X += 1
    ws.write(0, X, 'Country Name')