【问题标题】:Convert excel file to PDF using Python (MacOS) while retaining source formatting使用 Python (MacOS) 将 excel 文件转换为 PDF,同时保留源格式
【发布时间】:2021-05-17 16:45:50
【问题描述】:

我正在执行一项使用 Python 将 Excel 文件自动转换为 PDF 的任务。我能够通过以下方式实现这一目标:

  1. 将原始 excel 数据(基于定义的范围)转换为 pandas 数据框。
  2. 将数据框转换为 HTML 文件(中间步骤)。
  3. 将 HTML 文件转换为 PDF。

我在 MacOS 中执行此操作,它按预期工作。参考代码:

from openpyxl import load_workbook
import pdfkit as pdf
import pandas as pd
wb = load_workbook(filename = '4-Grain Advertising Report.xlsx', read_only = True, data_only=True)
ws = wb['Advertising 4 Grain P&L']

data_rows = []
for row in ws['K9':'S31']:
    data_cols = []
    for cell in row:
        data_cols.append(cell.value)
    data_rows.append(data_cols)

df = pd.DataFrame(data_rows)
df = df.replace([None], [''], regex = True)
df.to_html('test.html', header=None, index=False)
output = 'test_output.pdf'
pdf.from_file('test.html', output)

但是,如果我遵循此方法,我将无法保留在原始 Excel 电子表格中设置的格式选项(例如 - 单元格颜色/粗体标题等)。这给了我一个原始表格,其中包含 PDF 格式的值。

任何关于如何保留源格式并通过 Python 自动转换为 PDF 的建议都会非常有帮助。谢谢!

【问题讨论】:

    标签: python python-3.x excel


    【解决方案1】:

    您将无法使用 Pandas 保留格式。它根本不支持样式。您可以尝试使用其他工具,例如this

    【讨论】:

      猜你喜欢
      • 2012-03-25
      • 2012-02-03
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2020-02-29
      相关资源
      最近更新 更多