如何在使用python下载excel文件时将字符串转换为日期格式

2024-04-19 00:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标和困难在于将excel中的日期列数据从数字格式转换为日期格式

在我的python代码片段中,保存日期的变量是字符串类型

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

到目前为止还不错,但当我下载excel文件并访问包含日期数据的单元格时,格式单元格会将格式识别为数字(我不确定这句话是否值得一提)

无论如何,我希望日期数据的格式是date,而不是Number 我怎么做

这是我的密码:

# 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)

我读到xlrd库可以在这方面有所帮助,但我没有正确地使用它


Tags: 数据todaydatetimedatestyleresponse格式type
1条回答
网友
1楼 · 发布于 2024-04-19 00:42:52

答案基于xlsxwriter库的使用情况

通过下面的代码片段,我最终尝试下载xlsx文件,并在excel中以日期格式值而不是默认的数字格式值显示我的日期值

片段:

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

相关问题 更多 >