如何使用 Python 将 Excel 工作表保存为 PDF

问题描述 投票:0回答:1

我有一个包含多个工作表的 Excel 电子表格。我需要一个 Python 脚本来将每张纸保存为横向的 pdf,适合页面宽度,使用纸的名称作为 pdf 的名称。这是我到目前为止想出的:

import pandas as pd
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.page import PageMargins

# Load the Excel spreadsheet
file_name = 'A1 Marking Rubric 2023 in progress.xlsx'
xl = pd.ExcelFile(file_name)

# For each sheet in the workbook, create a PDF
for sheet_name in xl.sheet_names:
    # Load the sheet into a DataFrame
    df = pd.read_excel(file_name, sheet_name=sheet_name)

    # Set the output file name
    pdf_file_name = f"{sheet_name}"

    # Get the sheet dimensions
    wb = openpyxl.load_workbook(file_name)
    ws = wb[sheet_name]
    max_col = ws.max_column
    max_row = ws.max_row

    # Calculate the page width
    page_width = sum(ws.column_dimensions[get_column_letter(
        i)].width for i in range(1, max_col+1))

    # Set the page margins
    page_margins = PageMargins(left=0.25, right=0.25, top=0.75, bottom=0.75)

    # Save the sheet as a PDF
    with pd.ExcelWriter(pdf_file_name, engine='openpyxl') as writer:
        df.to_excel(writer, sheet_name=sheet_name, index=False)
        wb = writer.book
        ws = wb[sheet_name]
        ws.page_margins = page_margins
        ws.page_setup.fitToWidth = 1
        ws.page_setup.fitToHeight = 0

    # Move the PDF to the current directory
    import os
    os.replace(pdf_file_name, f"./{pdf_file_name}.pdf")

我最终在目标文件夹中得到了正确数量的文件,具有正确的名称,但每个文件都是

File not in PDF format or corrupted
。本主题的其他问题不使用 Python。谁能看出错误?

python excel pandas pdf openpyxl
1个回答
0
投票

下面的代码应该适合你

import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.page import PageMargins

# Load the Excel spreadsheet
file_name = 'A1 Marking Rubric 2023 in progress.xlsx'
wb = openpyxl.load_workbook(file_name)

# For each sheet in the workbook, create a PDF
for sheet_name in wb.sheetnames:
    # Set the output file name
    pdf_file_name = f"{sheet_name}.pdf"

    # Get the sheet dimensions
    ws = wb[sheet_name]
    max_col = ws.max_column
    max_row = ws.max_row

    # Calculate the page width
    page_width = sum(ws.column_dimensions[get_column_letter(
        i)].width for i in range(1, max_col+1))

    # Set the page margins
    page_margins = PageMargins(left=0.25, right=0.25, top=0.75, bottom=0.75)

    # Set the page setup
    ws.page_setup.paperSize = ws.PAPERSIZE_A4
    ws.page_margins = page_margins
    ws.page_setup.fitToWidth = 1
    ws.page_setup.fitToHeight = 0

    # Save the PDF file
    wb.save(pdf_file_name)
© www.soinside.com 2019 - 2024. All rights reserved.