How to make download link inside excel auto save

I was trying to make excel file using openpyxl v3.1.2 in Django, Python v3.9, the excel file contains link displayed as 'Click Here', those are links to files, despite the links are open correctly, but they are not save into the machine..

I mean they open in browser, or in the suitable program, but they are not saved (downloaded) into my machine.

How to make them downloaded directly into my machine, like when u download file from internet.

here is my code:

#views.py 
def export_applicants_xls(request, pk, applicant_id=None):
    job = get_object_or_404(Job, pk=pk)
    if applicant_id:
        candidate_list = Applicant.objects.filter(job=pk, pk=applicant_id)
    else:
        candidate_list = Applicant.objects.filter(job=pk)

    if not candidate_list:
        messages.error(request, _('No applicants for this job'), 'danger')
        return redirect('employer-job-detail', pk=pk)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    if applicant_id:
        response['Content-Disposition'] = f'attachment; filename=applicant_{applicant_id}_details.xlsx'
    else:
        response['Content-Disposition'] = f'attachment; filename=all_applicants_#{job.slug}.xlsx'

    wb = Workbook()
    ws = wb.active
    ws.title = 'Applicants'

    # Set header row in bold
    header_font = Font(bold=True)
    columns = [ 'CV File', 'ID card', 'Tawjihi file', 'University File', 'Experience File', 'Master file', 'Profession', 'Injury Insurance', 'Membership File', 'Temporary Membership']
 

  
    for col_num, column in enumerate(columns, 1):
        cell = ws.cell(row=1, column=col_num, value=column)
        cell.font = header_font
        ws.column_dimensions[get_column_letter(col_num)].width = 15  # Adjust column width

    # Populate data rows
    for row_num, applicant in enumerate(candidate_list, 2):
        row_data = [
            applicant.get_file_url('cv_file', request),
            applicant.get_file_url('id_card', request),
            applicant.get_file_url('tawjihi_file', request),
            applicant.get_file_url('uni_file', request),
            applicant.get_file_url('experience_file', request),
            applicant.get_file_url('master_file', request),
            applicant.get_file_url('profession_file', request),
            applicant.get_file_url('injury_insurance', request),
            applicant.get_file_url('membership_file', request),
            applicant.get_file_url('temporary_membership', request),
        ]

       
        for col_num, value in enumerate(row_data, 1):
            cell = ws.cell(row=row_num, column=col_num, value=value)
            if col_num in [34, 35, 36, 37, 38, 39, 40, 41, 42, 43]:
                if value:  # Check if the URL is not None
                    link_1(cell, value, display='Click Here')

    # Save workbook to response
    output = BytesIO()
    wb.save(output)
    response.write(output.getvalue())
    return response


def link_1(cell, link, display=None):
    cell.hyperlink = link
    cell.font = Font(u='single', color=colors.BLUE)
    if display is not None:
        cell.value = display

#models.py
   def get_file_url(self, field_name, request: HttpRequest):
        file_field = getattr(self, field_name)
        if file_field:
            return request.build_absolute_uri(f"{settings.MEDIA_URL}{str(file_field)}")
        return None

You can use Django's FileResponse.

    # Save workbook to response
    output = BytesIO()
    wb.save(output)
    output.seek(0)  # Rewind the buffer to the beginning after writing

    # Create a FileResponse with the BytesIO object as the file, and set the appropriate content type
    response = FileResponse(output, as_attachment=True, filename='your_workbook_name.xlsx', content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    # Return the response
    return response
Back to Top