You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MailMerge对象无法转为Unicode?Python模板文档打印方案咨询

解决MailMerge对象转Unicode的TypeError问题

我一眼就看出问题出在哪了——你把MailMerge对象直接传给win32api.ShellExecute()了,但这个函数需要的是文件路径字符串,不是MailMerge实例,这就是触发TypeError: Objects of type 'MailMerge' can not be converted to Unicode的核心原因。另外你的代码还有个隐藏问题:循环里复用同一个document对象,多次执行merge会把所有成员的内容叠加到同一个文档里,最后打印的内容会越来越多。

修复步骤

  • 每次循环都新建一个MailMerge实例,确保每个成员的文档都是独立的
  • 给每个生成的文档设置唯一文件名,避免覆盖之前的输出
  • 调用ShellExecute时,传入生成的docx文件路径,而不是MailMerge对象
  • (可选)打印完成后删除临时生成的文件,避免磁盘冗余

修复后的完整代码

from __future__ import print_function
from mailmerge import MailMerge
import os
import win32api
import win32print
import tempfile

# 读取并解析文本文件
text_file = open('J:\\cpletters15.txt')
courtesy_pay_list = text_file.readlines()
text_file.close()
delimeted_text = [line.split('\t') for line in courtesy_pay_list]

template_path = 'J:\\courtesy_pay_15_test.docx'
default_printer = win32print.GetDefaultPrinter()

# 循环处理每个成员
for idx, row in enumerate(delimeted_text[1:], 1):
    # 每次循环新建MailMerge实例,避免内容叠加
    document = MailMerge(template_path)
    
    # 合并当前成员的信息
    document.merge(
        SHARE_NBR = row[2],
        MEMBER_NBR = row[1],
        CITY = row[11],
        ADDRESS1 = row[9],
        ADDRESS2 = row[10],
        LAST_NAME = row[8],
        STATE = row[12],
        FIRST_NAME = row[7],
        ZIP = row[13],
        LETTER_DATE = row[4],
        BALANCE = row[6]
    )
    
    # 生成唯一的临时文件名,避免覆盖
    temp_file = os.path.join(tempfile.gettempdir(), f'member_letter_{idx}.docx')
    document.write(temp_file)
    
    # 调用ShellExecute打印文件,传入文件路径而非MailMerge对象
    win32api.ShellExecute(
        0,
        "print",
        temp_file,
        f'/d:"{default_printer}"',
        ".",
        0
    )
    
    # (可选)如果不需要保留临时文件,打印后删除
    # os.remove(temp_file)

额外说明

  • 我把路径里的单反斜杠改成了双反斜杠,避免Python把\c这类字符解析为转义序列
  • 使用tempfile.gettempdir()生成临时文件,更符合跨平台规范,也不会污染你的工作目录
  • 用enumerate给每个文档加索引,确保文件名唯一,不会被后续的文件覆盖

内容的提问来源于stack exchange,提问作者Tristochi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:23:02