簡體   English   中英

如何使用 Python 將 excel 轉換為水平方向的 pdf

[英]How to convert excel to pdf with orientation to horizontal using Python

我有一個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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM