以横向方式将excel转换为pdf

时间:2017-02-22 07:49:50

标签: python excel python-2.7 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()

唯一的问题是我需要这张桌子是横向的,我不知道如何制作这个规格。

我见过使用ws.PageSetup.Orientation = xlLandscape等代码的解决方案或其中的一些变体,但我相信这只适用于VBA /我无法找到python的正确语法。

非常感谢任何帮助或想法。

2 个答案:

答案 0 :(得分:1)

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

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()

只要您不保存更改,这不会影响原始文件,并且不需要使用vbscript宏的临时文件

答案 1 :(得分:0)

好的,所以我设法破解了一些我原先问过的代码。我确信有更好的方法可以解决这个问题,但对于那些坚持同一问题的人来说,这可能有所帮助。

我最终"保存为"将现有的.xlsx文件作为新的宏启用excel文件并输入在python中创建的宏。 VBA代码可以将文件更改为横向模式,然后导出为PDF。一旦宏运行,我删除.xlsm文件。如果excel应用程序尚未关闭,最后的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)
相关问题