Created
November 14, 2018 18:35
-
-
Save olivx/ba8d584d06e36bbf0c879b07069c71e1 to your computer and use it in GitHub Desktop.
formatando colunas ao exportar um dataframe com pandas para excel
This file contains hidden or 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
list_schedule = [] | |
for user in sc.candidates.all(): | |
data = dict( | |
email=user.email, | |
cpf=cpf, | |
phone=user_profile.phone1 | |
) | |
list_schedule.append(data) | |
df = pd.DataFrame(list_schedule) | |
if not df.empty: | |
# ordenando colunas no dataframe | |
df = df[['email', 'cpf', 'phone']] | |
output = StringIO.StringIO() | |
writer = pd.ExcelWriter(output, engine='xlsxwriter') | |
df.to_excel(writer, sheet_name=job_object.title, index=False) | |
# melhorando a formatação. | |
workbook = writer.book | |
worksheet = writer.sheets[job_object.title] | |
worksheet.set_zoom(90) | |
momey_format = workbook.add_format({'align': 'center', 'num_format': 'R$ #,##0', 'bold': True}) | |
porcent_format = workbook.add_format({'align': 'center', 'num_format': '0%', 'bold': True}) | |
number_format = workbook.add_format({'align': 'center', 'bold': True}) | |
unicode_format = workbook.add_format({'align': 'center'}) | |
# unicode format | |
for idx, col in enumerate(df): | |
if df[col].dtype == 'object': | |
header = df[[col]].astype(unicode).columns.values | |
header_len = len(header.max()) + 2 | |
column_len = df[[col]].astype(unicode).apply(lambda x: x.str.len()).max().max() + 2 | |
if header_len > column_len: | |
worksheet.set_column(idx, idx, header_len, unicode_format) | |
else: | |
worksheet.set_column(idx, idx, column_len, unicode_format) | |
# money format | |
worksheet.set_column('K:K', 25, number_format) | |
worksheet.set_column('N:N', 25, momey_format) | |
worksheet.set_column('O:O', 25, momey_format) | |
worksheet.set_column('P:P', 25, momey_format) | |
# porcent format | |
worksheet.set_column('H:H', 25, porcent_format) | |
worksheet.set_column('R:R', 25, porcent_format) | |
writer.save() | |
output.seek(0) | |
content_type_ = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' | |
response = HttpResponse(output.read(), content_type=content_type_) | |
out_format = 'attachment; filename=%s-%s.xlsx' % (slugify(job_object.title), date.today().isoformat()) | |
response['Content-Disposition'] = out_format | |
else: | |
messages.error(request, _('Não existe Agendamento para essa vaga')) | |
response = HttpResponseRedirect(reverse('jobapplicants', kwargs={'pk': job_object.pk })) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment