Search code examples
pythondownloadonclickxlsxxlsxwriter

how to download xlsx file in download folder using python


I've created code for download xlsx file using xlsxwriter python library.

File is downloading after onclick event but its not downloading in user's download folder.

its downloading in the project folder where that code file is located. I'm using pathlib library to find the user's download folder.

views.py for download xlsx :

def downloadFuelXlsx(request):
    downloads_path = str(Path.home() / "Downloads")
    print(downloads_path)
    workbook = xlsxwriter.Workbook("Fuel.xlsx") 
    print(workbook)
    worksheet = workbook.add_worksheet()

    """ Add a format for the header cells. """ 
    header_format = workbook.add_format(
        {
            "border": 1,
            "bg_color": "#C6EFCE",
            "bold": True,
            "text_wrap": True,
            "valign": "vcenter",
            "indent": 1,
        }
    )

    """ Create Excel"""

    #Create Heading and apply formatting
    heading1 = "Name"
    heading2 = "Fuel Type"
    heading3 = "Cost"

    worksheet.write("A1", heading1, header_format)
    worksheet.write("B1", heading2, header_format)
    worksheet.write("C1", heading3, header_format)

    length = 20 #Set the number as per number of rows required. This will give you 20 rows in data

    #The list inside source should dynamically come from Database
    for r in range(1, length, 1):
        worksheet.data_validation('B'+str(r+1), {'validate': 'list',
                                    'source': ['Petrol', 'Diesel', 'BioFuel'],
                                    })
    workbook.close()
    return workbook

urls.py:

urlpatterns = [
      path('download_fuel_xlsx', views.downloadFuelXlsx, name='download_fuel_xlsx'),
]

Html Code for onclick download xlsx:

<div class="col-lg-4 text-right">
 <i class="fa fa-check" style="font-size:25px;color:green;cursor: pointer;"> <a target="_blank" href="{% url 'shouldcost:download_fuel_xlsx' %}"></a></i>
</div>

Solution

  • It looks like you aren't using the downloads_path variable so you aren't opening the workbook in the downloads folder.

    Try replacing workbook = xlsxwriter.Workbook("Fuel.xlsx") with workbook = xlsxwriter.Workbook(f"{downloads_path}/Fuel.xlsx")