[英]Python xlsxwriter is converting date to number while writing xlsx
[英]number instead of date string when writing xlsx file
在LibreOffice xlsx單元中,值是這樣的:01/13/2016。 當我使用python2創建新的xlsx文件時,該01/13/2016轉換為42461。
python代碼
sheet1.write(row,col,sheet.cell(row,col).value)
tab_matching = 0
for sheet_name in book.sheet_names():
temp_sheet_name = sheet_name.lower()
if temp_sheet_name == tab_name:
tab_matching = 1
sheet = book.sheet_by_name(sheet_name)
temp_sheet_name = file_prefix+part_file_name+"_"+file_type+".xlsx"
if os.path.exists(detail_path):
xlsx_file_name = detail_path+"/"+temp_sheet_name
else:
xlsx_file_name = dirname+"/"+temp_sheet_name
new_book = xlsxwriter.Workbook(xlsx_file_name)
sheet1 = new_book.add_worksheet()
for row in range(sheet.nrows):
for col in range(sheet.ncols):
sheet1.write(row,col,sheet.cell(row,col).value)
new_book.close()
你能告訴我為什么會這樣嗎?
42461
是42461
月1日的基礎日期值。 要顯示日期而不是數字,請指定日期格式:
format1 = new_book.add_format({'num_format': 'mm/dd/yyyy'})
sheet1.write('B1', 42461, format1) # 04/01/2016
sheet1.write('B2', 42382, format1) # 01/13/2016
文檔位於http://xlsxwriter.readthedocs.io/working_with_dates_and_time.html 。
你可以做到這一點。
>>> import datetime
>>> today=datetime.datetime.now()
>>> today
datetime.datetime(2016, 8, 27, 1, 7, 1, 909049)
>>> value=today.strftime("%d/%m/%Y")
'27/08/2016'
>>> sheet1.write(row,col,sheet.cell(row,col).value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.