将横向转换为PDF格式

我想转换一个Excel表格到PDF,它与以下代码一起工作:

xlApp = client.Dispatch("Excel.Application") books = xlApp.Workbooks.Open('Table.xlsx') ws = books.Worksheets[0] ws.Visible = 1 ws.ExportAsFixedFormat(0, 'Table.pdf') books.Save() books.Close() 

唯一的问题是,我需要桌子是横向的,而且我对如何制定这个规范感到不知所措。

我已经看到解决scheme的代码,如ws.PageSetup.Orientation = xlLandscape或一些变化,但我相信这只适用于VBA /我无法find正确的Python语法。

任何帮助或想法将不胜感激。

更简单的方法是在打印前改变方向:

 def print_excel_worksheet_to_pdf(i_sz_excel_path, i_sz_ws_name, i_sz_pdf_path): excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = False #Keep the excel sheet closed excel.DisplayAlerts = False #"Do you want to over write it?" Will not Pop up try: wb_source = excel.Workbooks.Open(i_sz_excel_path) ws_source = wb_source.Worksheets(i_sz_ws_name) ws_source.PageSetup.Orientation = 2 # change orientation to landscape ws_source.Select() wb_source.ActiveSheet.ExportAsFixedFormat(0, i_sz_pdf_path) except Exception as e: print(e) excel.Application.Quit() 

只要不保存更改,这不会影响原始文件,并且不需要使用vbscriptmacros来创build临时文件

好吧,所以我设法把一些代码按照我最初的要求进行编译。 我相信还有更好的办法可以解决这个问题,但对于那些陷入同样问题的人来说,这可能会有所帮助。

我结束了“另存为”现有的.xlsx文件作为一个新的macros启用excel文件,并input在python中创build一个macros。 VBA代码可以将文件更改为横向模式,然后以PDF格式导出。 一旦macros运行完毕,我将删除.xlsm文件。 如果excel应用程序没有closures,最后的try语句可以防止发生错误。

 # Save as pdf # Start excel application xlApp = client.Dispatch("Excel.Application") # Open the table previously created books = xlApp.Workbooks.Open('Table.xlsx')) # xlmodule allows for insertion of VBA code which we will use to change orientation and save as pdf xlmodule = books.VBProject.VBComponents.Add(1) # VBACode is the VBA code used, sub ... is the name of the macro VBACode = '''Sub PDF_Creation() With Worksheets("Overlap Matrix").PageSetup .Orientation = xlLandscape .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = 1 End With Worksheets("Overlap Matrix").ExportAsFixedFormat _ Type:=xlTypePDF, _ Filename:="C:/.../PDF_test.pdf", _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=True End Sub''' # Now we add the VBA code as a macro to the excel sheet xlmodule.CodeModule.AddFromString(VBACode) # To use the VBA code we must first save the file as xlsm -> FileFormat 52 denotes xlsm books.SaveAs('Table', FileFormat=52) # Close the book so that we can reopen it as a macro enabled file books.Close() # Open the newly created xlsm file xlApp.Workbooks.Open(Filename='Table.xlsm', ReadOnly=1) # Run the macro xlApp.Application.Run('Table.xlsm!PDF_Creation') # Quit the application xlApp.Application.Quit() # Delete the macro file, we still have the file without macros as a backup # Use while loop to continue trying till we actually quit the excel application file_deleted = False while file_deleted is False: try: os.remove('Table.xlsm') file_deleted = True except WindowsError: sleep(0.5)