简体   繁体   English

使用openpyxl将日期格式写入excel文件时如何更改日期格式

[英]How to change the date format while writing it to excel file using openpyxl

I want to convert the date format from dd-mm-yy to mm-yy while writing it into excel file.我想将日期格式从dd-mm-yymm-yy同时将其写入 excel 文件。 I tried all the methods but to no success.我尝试了所有方法,但都没有成功。 I am trying to copy data from one excel file and paste it into another.我正在尝试从一个 Excel 文件中复制数据并将其粘贴到另一个文件中。 But the date messes up everything.但日期把一切都搞砸了。

This is my original Document.这是我的原始文档。 From where the code will copy the data:代码将从哪里复制数据: 这是我的原始文档。代码将从哪里复制数据

This is how it gets displayed in destination excel file:这是它在目标 excel 文件中的显示方式:
这就是它在目标 excel 文件中的显示方式。

I have used Openpyxl, Pandas for the same.我也用过 Openpyxl 和 Pandas。

If you have a variable with all the content you want to write, just use the datetime_format and NOT the date_format .如果您有一个包含要写入的所有内容的变量,只需使用datetime_format而不是date_format

For instance, I am deleting a sheet called ValorLiq and then rewriting it.例如,我正在删除一个名为ValorLiq的工作表,然后重写它。 I have the content I want to write in myFILE .我有我想在myFILE写入的内容。 The commands are:命令是:

fn = 'C:/Users/whatever/yourspreadsheet.xlsx'
writer=pd.ExcelWriter(fn,mode='a',engine='openpyxl',datetime_format='DD/MM/YYYY')
idx = writer.book.sheetnames.index('ValorLiq')
writer.book.remove(writer.book.worksheets[idx])
myFILE.to_excel(writer, merge_cells = False, sheet_name='ValorLiq')
writer.save()

The problem is that you are still writing datetimes - you need to convert them to a string before writing (you loose all but what you have inside the string) or set the number format of your cell:问题是您仍在写入日期时间 - 您需要在写入之前将它们转换为字符串(除了字符串中的所有内容,您都丢失了所有内容)或设置单元格的数字格式:

from openpyxl import Workbook                    # openpyxl  2.6.2
from openpyxl.utils import get_column_letter

import datetime

basedate = datetime.datetime.today() 

# create some demo dates, roughly -5 to +5 months
some_dates = [basedate + datetime.timedelta(days = i*30) for i in range(-5,6)]
print(some_dates)

# create a workbook
wb = Workbook() 
ws1 = wb.active
ws1.title = "dates"
ws1["A1"] = "Daaaaaaaaates"
# fill dates manually to enable cell formatting
for i, date in enumerate(some_dates,2):
    ws1[f"A{i}"] = date                # no format

    ws1[f"B{i}"] = date                # formatted to MM.YY
    cell = ws1.cell(column=2, row=i)   # get cell and change format
    cell.number_format = "MM.YY"       # use 'MM-YY' if you want a dash between month/year

    # uncomment if you want to store the stringified version directly
    # ws1[f"C{i}"] = date.strftime("%m.%y")

wb.save(filename = 'workbook.xlsx')

this gets you a printed list of这会给你一个打印的列表

[datetime.datetime(2019, 1, 9, 17, 1, 57, 329142), 
 datetime.datetime(2019, 2, 8, 17, 1, 57, 329142), 
 datetime.datetime(2019, 3, 10, 17, 1, 57, 329142), 
 datetime.datetime(2019, 4, 9, 17, 1, 57, 329142), 
 datetime.datetime(2019, 5, 9, 17, 1, 57, 329142), 
 datetime.datetime(2019, 6, 8, 17, 1, 57, 329142), 
 datetime.datetime(2019, 7, 8, 17, 1, 57, 329142), 
 datetime.datetime(2019, 8, 7, 17, 1, 57, 329142), 
 datetime.datetime(2019, 9, 6, 17, 1, 57, 329142), 
 datetime.datetime(2019, 10, 6, 17, 1, 57, 329142), 
 datetime.datetime(2019, 11, 5, 17, 1, 57, 329142)]

and an exported file (OpenOffice used to open) that looks like:和一个导出的文件(OpenOffice 用于打开),如下所示:

导出的 xlss

HTH HTH

To achieve what you want, a named style needs to be created and assigned for each cell.为了实现您想要的,需要为每个单元格创建和分配一个命名样式。 Here is a working example:这是一个工作示例:

import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import NamedStyle
# Create a dataframe having a column of dates
df = pd.DataFrame({'DATE':pd.date_range(start='2018-1-1', end='2019-1-1')})
df = df.assign(DATE2=df["DATE"])
df = df.assign(DATE3=df["DATE"])
# Create a excel work book
ewb = pd.ExcelWriter('test.xlsx', engine="openpyxl")
# Create a named style
nsmmyy=NamedStyle(name="cd1", number_format="MM-YY")
nsmmmyy=NamedStyle(name="cd2", number_format="MMM-YY")
nsbyy=NamedStyle(name="cd3", number_format="MMMM-YY")
# Write dataframe to workbook
df.to_excel(excel_writer=ewb, sheet_name="SHT1")
# Get the work book by name
ws = ewb.book["SHT1"]
# For each cell in the column set the named style
# Add +2 to the number of rows since excel index starts from 1
for i in range(1, len(df) + 2):
    # Pass column argument as 2, since column 1 will have dataframe index
    ws.cell(row=i, column=2).style = nsmmyy
    ws.cell(row=i, column=3).style = nsmmmyy
    ws.cell(row=i, column=4).style = nsbyy
# Save work book
ewb.save()

This is how the resultant excel sheet would look like:这是生成的 excel 表的样子:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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