简体   繁体   中英

How to convert a string to date format when downloading an excel file using python

My aim and the difficulty found on that is to convert my Date column data in excel from Number format to Date format.

In my python snippet the variable holding the date is type of string.

current_date=datetime.today().strftime('%-d/%-m/%Y')

So far so good, but when I download my excel file and access the cell with the date data the Format Cells recognize the format as Number(I am not sure if this statement worths mentioning).

Anyway, I want the date data to be of format Date and not the format of Number How can i do it?

Here is my code:

# content-type of response
response = HttpResponse(content_type='application/ms-excel')
#decide file name
response['Content-Disposition'] = 'attachment; filename="export.xls"'
#creating workbook
wb = xlwt.Workbook(encoding='utf-8')
#adding sheet
ws = wb.add_sheet("export")
# Sheet header, first row
row_num = 0
#style
font_style = xlwt.XFStyle()
font_style.font.bold = True
#date(string)
current_date=datetime.today().strftime('%-d/%-m/%Y')
...
ws.write(row_num,1,current_date)

I read that xlrd library could help on that but I didn't manage to use it properly.

The answer is based on the usage of xlsxwriter library.

With the below snippet of code I finally tried to download the xlsx file and to present my date values in excel as Date format values instead of Number format values used to be by default.

snippet:

from xlsxwriter.workbook import Workbook
from io import BytesIO

# create a workbook in memory
output = BytesIO()
wb = Workbook(output)
ws = wb.add_worksheet('export') 
...
current_date = datetime.now()
format2 = wb.add_format({'num_format': 'dd/mm/yy'})
...
ws.write(row_num,1,current_date,format2)
wb.close()
# construct response
output.seek(0)
response = HttpResponse(output.read(), content_type='application/ms-excel')
response['Content-Disposition'] = "attachment; filename=export.xlsx"
return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM