[英]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.