是否有方法将excel文件中的文本格式更改为用于邮件合并的日期格式?

2024-04-27 02:56:49 发布

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

希望你保持安全

我正在尝试执行邮件合并,它将从名为“source1”的excel文件中捕获数据,并使用template.doc文件创建word模板

输出正常,但excel文件中某些列(如日期)的格式需要固定。由于某些原因,日期包括小时

示例生成的模板中的输出为2020-12-12 00:00:00,而所需格式必须为2020年12月12日

下面是代码

from mailmerge import MailMerge

import openpyxl

import datetime

wb=openpyxl.load_workbook('source1.xlsx')

sheet= wb['Sheet1']

max_col = sheet.max_row

sheet.delete_rows(sheet.min_row,1)

for i in range(1, max_col):

    template='template.docx'

    document1=MailMerge(template)

    document1.merge(

        first_name = str(sheet.cell(row=i,column=1).value),

        last_name = str(sheet.cell(row = i, column = 2).value),

        salary = str(sheet.cell(row = i, column = 3).value),

        Date = str (sheet.cell(row = i, column =4 ).value),

        date1='{:%d-%b-%Y}'.format(Date),

      #  country = str ( sheet.cell(row = i, column = 5). value),

       # Title = str(sheet.cell(row = i, column = 6).value),

       # item = str(sheet.cell(row = i, column = 7).value),

      # price = '$'+str(sheet.cell(row = i, column=8).value),

      #  quantity = str(sheet.cell(row=i, column = 9).value),

       # total = str(sheet.cell(row = i, column = 10).value),

        )

    document1.write('Letter for ' +str(sheet.cell(row=i, column=1).value)+'.docx')

我试着用

    Date = str (sheet.cell(row = i, column =4 ).value),

    date1='{:%d-%b-%Y}'.format(Date),

但它给了我一个错误“日期未定义”


Tags: 文件import模板datevaluecellcolumntemplate
1条回答
网友
1楼 · 发布于 2024-04-27 02:56:49

有两个问题:

  1. 您试图转换日期格式时出错。为此,您需要使用datetime库,而不是字符串格式
  2. Datedocument1.merge()的命名参数,因此不能在函数调用中访问它。您可以从库的the example usage中看到document.merge获取与合并字段相对应的kwargs,但您正在尝试在此函数调用中创建正则变量

要解决此问题,应在函数调用之前进行日期转换:

import datetime as dt

...

for i in range(1, max_col):

    # Convert the format here
    Date = str(sheet.cell(row = i, column =4 ).value) # Assuming format e.g. 2020-05-01
    date1 = dt.datetime.strptime(Date, '%Y-%m-%d').strftime('%d-%b-%Y')

    template = 'template.docx'
    document1 = MailMerge(template)
    document1.merge(first_name = str(sheet.cell(row=i,column=1).value),
                    last_name = str(sheet.cell(row = i, column = 2).value),
                    salary = str(sheet.cell(row = i, column = 3).value),
                    date1 = date1)

    document1.write('Letter for ' +str(sheet.cell(row=i, column=1).value)+'.docx')

相关问题 更多 >