Excel COM对象忽略打印区域



使用Excel COM对象打开Excel工作簿

app = gencache.EnsureDispatch("Excel.Application")
doc = app.Workbooks.Open(filepath)

所有打印区域都被删除,但当文件正常打开时,它们可以通过VBA访问。

本地化版本的MS Excel在作为COM对象访问时忽略打印区域和标题,因此如果需要,必须为每个工作表显式指定PageSetup.PrintArea|PrintTitleColumns|PrintTitleRows

for sh in self.doc.Worksheets: #explicitly specify print areas and titles
    for name in sh.Names:
        if name.Name.endswith("!Print_Area"):
            sh.PageSetup.PrintArea = name.RefersTo
        elif name.Name.endswith("!Print_Titles"):
            #protect comma symbol in sheet name
            chunks = name.RefersTo.replace(sheet.Name, "[sheet_name]").split(",")
            chunks = [i.replace("[sheet_name]", sheet.Name) for i in chunks]
            if len(chunks) == 1:
                try: sh.PageSetup.PrintTitleColumns = chunks[0]
                except: sh.PageSetup.PrintTitleRows = chunks[0]
            else: sh.PageSetup.PrintTitleColumns, sh.PageSetup.PrintTitleRows = chunks

来源:Excel -> PDF (ExportAsFixedFormat)

UPD:支持表名中带逗号

最新更新