我有一个excel sheet
,我想要转换为pdf使用python
。我可以使用以下代码来完成此操作:
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
发布于 2020-09-28 12:45:42
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
https://stackoverflow.com/questions/64096023
复制相似问题