【发布时间】:2022-08-24 19:56:16
【问题描述】:
我有一些代码可以将 excel 文件从 excel 转换为 PDF。虽然我知道 openpyxl 具有分配列宽值、换行和添加单元格边框的方法,但我正在寻找一种使用 win32com 模块的方法。这是因为我已经使用 win32com 打开了 Excel 文件,并且无需再次使用 openpyxl 加载 Excel 文件,可以节省执行时间。
# Import Module
from win32com import client
# Open Microsoft Excel
excel = client.gencache.EnsureDispatch(\'Excel.Application\')
# Make excel work in the background without appearing
excel.Visible = False
# Read Excel File
wb = excel.Workbooks.Open(r\'C:\\Spaced out data.xlsx\')
ws = wb.Worksheets(\'Sheet1\')
# Adjust page setup to landscape
ws.PageSetup.Orientation = 1
# Set Zoom to false because you want to fit all columns to the width of 1 page.
ws.PageSetup.Zoom = False
# Allow rows to be on multiple pages
ws.PageSetup.FitToPagesTall = False
# Fit all columns to the width of 1 page.
ws.PageSetup.FitToPagesWide = 1
# Convert into PDF File
ws.ExportAsFixedFormat(0, r\'C:\\Spaced out data.pdf\')
wb.Close(SaveChanges=False)
excel.Quit()