写入 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()

你能告诉我为什么会这样吗?

你可以做到这一点。

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

42461 是 04/01/2016 的基础日期值。要显示日期而不是数字,请指定日期格式:

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