In Django app (ubuntu server online) I know how to create an xlsx file from HttpResponse with openpyxl using this piece of code :
views.py
def export_to_excel(request):
movie_queryset = models_bdc.objects.all()
response = HttpResponse(
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
response['Content-Disposition'] = 'attachment; filename={date}-movies.xlsx'.format(
date=datetime.now().strftime('%Y-%m-%d'),
)
workbook = Workbook()
# Get active worksheet/tab
worksheet = workbook.active
worksheet.title = 'Movies'
# Define the titles for columns
columns = [
'ID',
'Title',
'Description',
'Length',
'Rating',
'Price',
]
row_num = 1
# Assign the titles for each cell of the header
for col_num, column_title in enumerate(columns, 1):
cell = worksheet.cell(row=row_num, column=col_num)
cell.value = column_title
# Iterate through all movies
#try to sort by index here and ignore empty rows
# apply a save to DB before export to excel to get the latest changes
for movie in movie_queryset:
row_num += 1
# Define the data for each cell in the row
row = [
movie.bdc_description_1,
movie.bdc_description_2,
movie.bdc_description_3,
movie.bdc_description_4,
movie.bdc_description_5,
movie.bdc_description_1,
]
# Assign the data for each cell of the row
for col_num, cell_value in enumerate(row, 1):
cell = worksheet.cell(row=row_num, column=col_num)
cell.value = cell_value
workbook.save(response)
return response
But I would also like to convert the generated .xlsx as a .pdf file.
I don’t know what approach is the best :
- Directly save the response as a .pdf file
- Wait for the xlsx to be created and saved and then convert it to pdf file.
I tried to use :
subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", response])
after the line
workbook.save(response)
but it gave me this error :
expected str, bytes or os.PathLike object, not HttpResponse
Thanks for the help