【问题标题】:how to convert excel to PDF using Python如何使用 Python 将 Excel 转换为 PDF
【发布时间】:2021-05-30 23:14:10
【问题描述】:

我有一个主文件夹,其中包含一些 .xlsx、.ipynb、.jpeg 和一些子文件夹。 现在我想将我主文件夹中的所有 .xlsx 文件转换为 PDF。

这是我每天必须做的例行工作,如果你能教我如何用 python 做,我将不胜感激。

*所有文件在工作簿的第一张表中都有一些数据

谢谢

【问题讨论】:

标签: python excel pdf automation


【解决方案1】:

试试这样:

saveFormat = self.SaveFormat

workbook = self.Workbook(self.dataDir + "Book1.xls")

#Save the document in PDF format

workbook.save(self.dataDir + "OutBook1.pdf", saveFormat.PDF)

\# Print message

print "\n Excel to PDF conversion performed successfully."

【讨论】:

  • 什么是“.self” 它给了我这个错误“NameError: name 'self' is not defined”
【解决方案2】:

有什么你已经尝试过的吗?

我建议测试 pywin32。

  1. 下载pywin32
python3 -m pip install pywin32
  1. 编写脚本以实现自动化。
import win32com.client
from pywintypes import com_error

# Path to original excel file
WB_PATH = r'~/path/to/file.xlsx'
# PDF path when saving
PATH_TO_PDF = r'~/path/to/file.pdf'
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
try:
    print('Start conversion to PDF')
    # Open
    wb = excel.Workbooks.Open(WB_PATH)
    # Specify the sheet you want to save by index. 1 is the first (leftmost) sheet.
    ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12]
    wb.WorkSheets(ws_index_list).Select()
    # Save
    wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
    print('failed.')
else:
    print('Succeeded.')
finally:
    wb.Close()
    excel.Quit()

【讨论】:

  • 是的,我在谷歌搜索时看到了这个脚本,但无法从这里找到一个文件夹中的多个 excel
  • 没有通过 Dispatch:pywintypes.com_error: (-2147023728, 'Element not found.', None, None) 使用 Conda Python 3.8.3 和 pywin32 v227
猜你喜欢
  • 2019-11-26
  • 2012-08-05
  • 2020-02-29
  • 2021-01-13
  • 1970-01-01
  • 2011-05-26
  • 2017-01-13
  • 2018-01-27
  • 1970-01-01
相关资源
最近更新 更多