PyPDF2 AttributeError: 'Worksheet' object has no attribute 'export_pdf'
时间: 2023-09-23 20:04:54 浏览: 195
这个错误是因为 `export_pdf` 方法是在 `openpyxl` 模块中定义的,而不是在 `PyPDF2` 模块中定义的。如果你想将一个 Excel 文件转换成 PDF,可以使用 `openpyxl` 模块来实现。下面是一个简单的示例代码:
```python
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.page import PageMargins
from io import BytesIO
from reportlab.pdfgen import canvas
from PyPDF2 import PdfFileWriter, PdfFileReader
def convert_excel_to_pdf(excel_file_path, pdf_file_path):
# Load the workbook
wb = load_workbook(excel_file_path)
# Select the active worksheet
ws = wb.active
# Set the page margins
ws.page_margins = PageMargins(left=0.5, right=0.5, top=0.5, bottom=0.5)
# Get the dimensions of the worksheet
rows = ws.max_row
cols = ws.max_column
# Create a new PDF file
pdf = canvas.Canvas(pdf_file_path)
# Iterate over the rows and columns of the worksheet
for row in range(1, rows + 1):
for col in range(1, cols + 1):
# Get the cell value
cell_value = ws.cell(row=row, column=col).value
# Get the cell width and height
cell_width = ws.column_dimensions[get_column_letter(col)].width
cell_height = ws.row_dimensions[row].height
# Set the font size and style
pdf.setFont("Helvetica", 12)
# Write the cell value to the PDF file
pdf.drawString(col * cell_width + 10, 800 - row * cell_height - 10, str(cell_value))
# Save the PDF file
pdf.save()
# Merge the PDF files
input_pdf = PdfFileReader(BytesIO(open(pdf_file_path, 'rb').read()))
output_pdf = PdfFileWriter()
output_pdf.addPage(input_pdf.getPage(0))
output_pdf.write(open(pdf_file_path, 'wb'))
```
这个函数会将指定的 Excel 文件转换成 PDF 文件,并保存在指定的位置。你可以调用这个函数来解决你遇到的问题。
阅读全文