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:用逗号支持表名