【发布时间】: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