【问题标题】:Python + Win32: Paste header from one Excel workbook to the top of anotherPython + Win32:将标题从一个 Excel 工作簿粘贴到另一个 Excel 工作簿的顶部
【发布时间】:2019-08-01 17:14:11
【问题描述】:

我想自动格式化 Excel 报告。我使用 Python 为报告生成原始数据,但在提交给项目经理之前,它们需要漂亮的格式(颜色、粗体、边框)。

我目前的方法是使用pywin32 包,从模板文件中复制标题,并将其粘贴到我的输出报告中。

我在使用.Paste() 方法时遇到问题,例如,如果我尝试使用.Paste(Destination=Range('A1:A100') 指定目标,则会引发错误。如果我尝试output_worksheet.used_range.Paste(),它也不会将used_range 识别为有效。

此外,我当前的代码不会退出 Excel。

最后我的代码将标题粘贴到第 16 行,而不是从顶部开始:

template_path = tests.path + r"\Box Tracking Report Regents Template.xlsx"
timestamp = datetime.datetime.now().strftime("%m-%d-%Y %I%M%p")
output_path = tests.path + r"\Box Tracking Report " + timestamp + ".xlsx"

# (... write my pandas dataframe in ...) 

def paste_formatting(tab_name):
    excel_instance = win32com.client.gencache.EnsureDispatch("Excel.Application")
    template = excel_instance.Workbooks.Open(template_path)
    template_workbook = excel_instance.Workbooks.Item(1)
    template_worksheet = template_workbook.Worksheets(tab_name)
    used_range = template_worksheet.UsedRange
    used_range.Copy()
    output_excel = excel_instance.Workbooks.Open(output_path)
    output_workbook = excel_instance.Workbooks.Item(2)
    output_worksheet=output_workbook.Worksheets(tab_name)
    output_worksheet.Paste()
    output_workbook.Close()
    template_workbook.Close()

paste_formatting('Regents Box Tracking Report')

这是我得到的:

【问题讨论】:

  • 只将第一个单元格放入 Destination=Range('A1') 是否有效?
  • output_worksheet.Paste(Destination=output_worksheet.Range("A1")) 不起作用,output_worksheet.Paste(Destination="A1") 也不起作用,output_worksheet.Range("A1").PasteSpecial() 也不起作用:'(
  • 谢谢。抱歉,我没有看到 - 它帮助我给出了答案。

标签: python excel winapi pywin32 win32com


【解决方案1】:

@chucklukowski 的评论:

def paste_formatting(tab_name):
    excel_instance = win32com.client.gencache.EnsureDispatch("Excel.Application")
    template = excel_instance.Workbooks.Open(template_path)
    template_workbook = excel_instance.Workbooks.Item(1)
    template_worksheet = template_workbook.Worksheets(tab_name)
    used_range = template_worksheet.UsedRange
    used_range.Copy()
    output_excel = excel_instance.Workbooks.Open(output_path)
    output_workbook = excel_instance.Workbooks.Item(2)
    output_worksheet=output_workbook.Worksheets(tab_name)
    output_worksheet.Paste(output_worksheet.Range('A1'))
    output_workbook.Save()
    output_workbook.Close()
    template_workbook.Close()
    excel_instance.Quit()
    del excel_instance

paste_formatting('Regents Box Tracking Report')

仍然很混乱,但可能比从模板本身调用 Excel VBA 宏更好(这将是我最后的方法)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2021-06-16
    相关资源
    最近更新 更多