Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created May 17, 2018 19:42
Show Gist options
  • Save rg3915/e965172a5007feb486825a6256d8f2ed to your computer and use it in GitHub Desktop.
Save rg3915/e965172a5007feb486825a6256d8f2ed to your computer and use it in GitHub Desktop.
Import Export Python to XLSX example
import xlrd
import xlwt
def salvar_xlsx(lista):
''' Exportar dados em XLSX '''
result = lista
# response = HttpResponse(content_type='application/ms-excel')
date_ = timezone.now().strftime('%y%m%d%H%M%S')
filename = "/tmp/example_{}.xlsx".format(date_)
# response['Content-Disposition'] = 'attachment; filename=%s' % filename
response = filename
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Contatos')
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ('NOME', 'EMAIL', 'CPF', )
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
rows = lista
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
filename = '/tmp/example.xlsx'
workbook = xlrd.open_workbook(filename)
sheet = workbook.sheet_by_index(0)
for row in range(sheet.nrows):
print(sheet.row(row)[0].value)
# print(sheet.cell(row,0).value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment