使用 xlwings 将 Excel 打印为 pdf

Ste*_*rpe 2 python xlwings

我正在尝试使用 .pdf 格式将 Excel 文件打印为 pdf xlwings。我正在使用excel api这个。

我已经通过两种方式尝试过:

1/ 使用PrintOut()PrintToFile参数的调用:

 wb.api.PrintOut(PrintToFile=True, PrToFileName="5.pdf", Preview=True)
Run Code Online (Sandbox Code Playgroud)

这里的问题是 Excel 只是打印文件,而忽略了我的其他设置。

2/ 使用 ExportAsFixedFormat

 wb.api.ExportAsFixedFormat(0, str(SwmId) + ".pdf")
Run Code Online (Sandbox Code Playgroud)

这里 Excel 闪烁了一下,但最终没有做任何事情。

作为记录:我不能使用宏并从 Python 调用它,因为我有大约一千个这样的 Excel 文件。所以,我不能把宏放在每一个中。在 VBA 中创建自定义函数而不是在每个文件中调用它可能是一种解决方法。但是,老实说,如果我可以在一行代码中直接从 Python 执行此操作会更容易。

Xuk*_*rao 5

以下是在我的机器上将 excel 工作簿打印为 pdf 的独立代码示例(使用该ExportAsFixedFormat方法):

# Environment
# -----------
# OS: Windows 10
# Excel: 2013
# python: 3.7.4
# xlwings: 0.15.8

import os
import xlwings as xw

# Initialize new excel workbook
book = xw.Book()
sheet = book.sheets[0]
sheet.range("A1").value = "dolphins"

# Construct path for pdf file
current_work_dir = os.getcwd()
pdf_path = os.path.join(current_work_dir, "workbook_printout.pdf")

# Save excel workbook to pdf file
print(f"Saving workbook as '{pdf_path}' ...")
book.api.ExportAsFixedFormat(0, pdf_path)

# Open the created pdf file
print(f"Opening pdf file with default application ...")
os.startfile(pdf_path)
Run Code Online (Sandbox Code Playgroud)

  • 我认为在这里提到“ExportAsFixedFormat”无法理解相对路径非常重要。只有绝对路径才有效。 (3认同)