【问题标题】:How to convert excel to pdf with orientation to horizontal using Python如何使用 Python 将 excel 转换为 pdf 并定向为水平
【发布时间】:2021-01-13 16:08:45
【问题描述】:

我有一个excel sheet,我想使用python 将其转换为pdf。我可以使用下面的代码来做到这一点:

import win32com.client
from pywintypes import com_error

WB_PATH = 'test.xls'
PATH_TO_PDF = 'test.pdf'

excel = win32com.client.Dispatch("Excel.Application")

excel.Visible = False

try:
    wb = excel.Workbooks.Open(WB_PATH)
    ws_index_list = [1]
    wb.WorkSheets(ws_index_list).Select()
    wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
    print('failed.')
else:
    print('Succeeded.')
finally:
    wb.Close()
    excel.Quit()

这工作正常,但问题是它在垂直布局中将 excel 转换为 pdf。我在excel中有很多列,因为有些列进入了第二页,看起来不太好。下面是截图:

以上是excel表格截图。

上图是 pdf 的第一页,其中包含直到滚动停止时间列的数据,其余包含在第二页中:

如何将方向更改为水平,以便所有列都适合第一页。请帮忙。谢谢

更新代码:

import win32com.client
from pywintypes import com_error


WB_PATH = 'test.xls'

PATH_TO_PDF = 'test.pdf'

excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False

try:
    wb = excel.Workbooks.Open(WB_PATH)
    wb.Worksheets("sheet")

    ws_index_list = [1]
    ws_source = wb.WorkSheets(ws_index_list)
    ws_source.PageSetup.Orientation = 2
    ws_source.Select()

    wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
    print('failed.')
else:
    print('Succeeded.')
finally:
    wb.Close()
    excel.Quit()

但上面的代码给出了错误:

AttributeError: <unknown>.PageSetup

【问题讨论】:

    标签: python excel pdf orientation win32com


    【解决方案1】:
    import win32com.client
    from pywintypes import com_error
    
    WB_PATH = 'test.xls'
    PATH_TO_PDF = 'test.pdf'
    
    excel = win32com.client.Dispatch("Excel.Application")
    
    excel.Visible = False
    
    try:
        wb = excel.Workbooks.Open(WB_PATH)
        ws_source.PageSetup.Orientation = 2 # orient the format before you print to pdf
        ws_index_list = [1]
        wb.WorkSheets(ws_index_list).Select()
        wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
    except com_error as e:
        print('failed.')
    else:
        print('Succeeded.')
    finally:
        wb.Close()
        excel.Quit()
    # I'm not a very experienced programmer but this should help. I would orient
    # the file first before printing it to pdf
    

    【讨论】:

    • 什么是ws_source
    • 我已经更新了代码但是它给出的错误,你能检查一下
    猜你喜欢
    • 2021-05-30
    • 1970-01-01
    • 2019-11-26
    • 2015-07-14
    • 2012-08-05
    • 2020-02-29
    • 2022-01-01
    • 1970-01-01
    • 2018-05-26
    相关资源
    最近更新 更多