I am trying to create excell report with django workbook and workseet as below.
def print_assistant_notes(request):
if request.method == 'GET':
notes = AssistantNotes.objects.filter(notedate=datetime.today().date()).order_by("time")
workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "assistant_notes.xlsx"))
worksheet = workbook.active
title_cell = worksheet["A%d" % (1,)]
title_cell.value = "Assistant Notes [ "+str(datetime.today().date())+" ] "
row = 3
for note in notes:
time_cell = worksheet["A%d" % (row,)]
category_cell = worksheet["B%d" % (row,)]
note_cell = worksheet["C%d" % (row,)]
time_cell.value = note.time
category_cell.value = note.categories
note_cell.value = note.dailynote
row = row + 1
tmp_file = tempfile.NamedTemporaryFile()
workbook.save(tmp_file.name)
response = HttpResponse(smart_str(tmp_file.read()), content_type='application/vnd.ms-excel')
response["Content-Disposition"] = 'attachment; filename="assistant_notes.xlsx"'
return response
When i print report i get excell report as below in red color data. But i want it to be formatted as blue colored format. Because notes colum does not fit in print area as i mentioned it with blue arrow. So i can say that my codes are generating report as the red part. But i want it to fit in the printable area in blue part. So i want to be able to set cell sizes. And text will fit in that cell size left to right. Up to down cell size will be dynamic as text size may change.
If you're using openpyxl
, you can actually change the styles of your cells, as outlined in the documentation:
from openpyxl.styles import Alignment
note_cell.alignment = Alignment(wrap_text=True)
Or create an alignment
object before your for...
loop and reuse it:
al = Alignment(wrap_text=True)
for note in notes:
...
note_cell = worksheet["C%d" % (row,)]
note_cell.alignment = al
which will be more memory-efficient.