Created
April 26, 2017 14:53
-
-
Save rg3915/91310e262e43a87d26762f5a814fa716 to your computer and use it in GitHub Desktop.
Export Excel with xlwt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xlwt | |
def export_xls(model_='User', file_name='export.xls', queryset=None, columns_=None): | |
response = HttpResponse(content_type='application/ms-excel') | |
response['Content-Disposition'] = 'attachment; filename="%s"' % file_name | |
wb = xlwt.Workbook(encoding='utf-8') | |
ws = wb.add_sheet(model_) | |
# Sheet header, first row | |
row_num = 0 | |
font_style = xlwt.XFStyle() | |
font_style.font.bold = True | |
# columns = ['Nome', 'Sobrenome', 'E-mail', 'Nascimento', 'Criado em'] | |
columns = columns_ | |
for col_num in range(len(columns)): | |
ws.write(row_num, col_num, columns[col_num], font_style) | |
# Sheet body, remaining rows | |
default_style = xlwt.XFStyle() | |
# 'first_name', 'last_name', 'email', 'birthday', 'created' | |
# rows = model_.objects.all().values_list(values_) | |
rows = queryset | |
for row, rowdata in enumerate(rows): | |
row_num += 1 | |
for col, val in enumerate(rowdata): | |
if isinstance(val, datetime): | |
val = val.strftime('%d/%m/%Y %H:%M') | |
elif isinstance(val, date): | |
val = val.strftime('%d/%m/%Y') | |
ws.write(row_num, col, val, default_style) | |
wb.save(response) | |
return response | |
def export_tasks_xls(request): | |
model_ = 'Task' | |
file_name = 'tasks.xls' | |
queryset = Task.objects.all().values_list('creator__first_name', | |
'to_do__description', | |
'to_do__next_contact', | |
'to_do__status', | |
'to_do__employee__user__first_name', | |
'created') | |
# Chama a função que retorna get_FOO_display manualmente. | |
# get_field_display_values_list(queryset, 'to_do__status', STATUS) | |
# get_field_display(query_, 'to_do__status', STATUS) | |
columns_ = ['Criado por', 'Descrição', | |
'Próximo contato', 'Status', 'Atribuido a', 'Criado em'] | |
response = export_xls(model_, file_name, queryset, columns_) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment