WIN32COM将多张工作表保存/导出为PDF [英] WIN32COM saving/exporting multiple sheets as PDF

查看:74
本文介绍了WIN32COM将多张工作表保存/导出为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个工作簿中选择多个工作表(按特定顺序),然​​后使用win32com将它们导出为单个PDF.我试过了:

I'd like to select multiple sheets (in a certain order) in a workbook and export them as a single PDF using win32com. I tried:

wb_HC.Sheets(['sheetname1','sheetname2']).ExportAsFixedFormat(0, workdir+'\\'+run_date+'_MD_Summary.pdf')

但这不起作用.我知道在VBA中,工作表可以称为工作表数组:

But this does not work. I know that in VBA sheets can be called as an array of sheets:

Array(sheets(1), sheets(2))

但是我认为这不等同于Python中的list().

But I think this is not equivalent to list() in Python.

推荐答案

考虑使用Python的列表 [] 方法,该方法可能对应于VBA的 Array().将其应用于通过工作表索引号或工作表名称的 Worksheets()方法.然后在 ExportAsFixedFormat 中用 xlApp.ActiveSheet 限定该方法:

Consider using Python's list [] method which could correspond to VBA's Array(). Apply it to the Worksheets() method passing either Sheet index number or Sheet name. Then in the ExportAsFixedFormat qualify the method with xlApp.ActiveSheet:

import os
import win32com.client

workdir = "C:\\Path\\To\\Working\\Directory"
rundate = '2016-09-11'

try:
    xlApp = win32com.client.Dispatch("Excel.Application")
    wb = xlApp.Workbooks.Open(os.path.join(workdir, 'ExcelFile.xlsx'))

    wb.Worksheets(["Sheet1", "Sheet2"]).Select()

    xlTypePDF = 0
    xlQualityStandard = 0

    xlApp.ActiveSheet.ExportAsFixedFormat(xlTypePDF, 
                                          os.path.join(workdir, run_date+'_MD_Summary.pdf'), 
                                          xlQualityStandard, True, True)    
except Exception as e:
    print(e)

finally:    
    wb.Close(False)
    xlApp.Quit

    wb = None
    xlApp = None

顺便说一句,请确保将处理内容包装在 try/except/finally 块中.否则,您遇到的任何错误都将使Excel.exe在后台进程中运行.在这种设置中,脚本始终关闭工作簿,并且不管错误如何都未初始化COM对象.VBA中的对应对象是 On Error Goto ... 处理(另一种最佳实践方法).

By the way, be sure to wrap your processing in try/except/finally blocks. Otherwise, any error you encounter will leave the Excel.exe running in background process. In this setup, the script always closes workbook and uninitializes the COM object regardless of error. The counterpart in VBA would be the On Error Goto ... handling (another best practice method).

这篇关于WIN32COM将多张工作表保存/导出为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆