Convert Excel to PDF using Python
There are various ways to convert an Excel file to a PDF using Python. One popular method is by using the library pyfpdf
.
Installation
To install pyfpdf
, you can use pip:
$ pip install fpdf
Example Code
Here is an example code snippet that shows how to convert an Excel file to a PDF using pyfpdf
:
from fpdf import FPDF import xlrd # Read the Excel file workbook = xlrd.open_workbook('input.xlsx') sheet = workbook.sheet_by_index(0) # Initialize the PDF object pdf = FPDF() pdf.set_auto_page_break(auto=True, margin=15) pdf.add_page() # Set font for the PDF pdf.set_font('Arial', 'B', 16) # Loop through rows in the Excel file and add them to the PDF for row_num in range(sheet.nrows): row_data = sheet.row_values(row_num) for cell_data in row_data: pdf.cell(40, 10, str(cell_data), 1, 0) # Save the PDF file pdf.output('output.pdf') print('PDF file created successfully')
Run the Code
Save the above code snippet as a Python file (e.g., convert_excel_to_pdf.py
) and run it using the command line:
$ python convert_excel_to_pdf.py
Conclusion
Converting an Excel file to a PDF using Python is a simple process with the help of libraries like pyfpdf
. By following the example code provided in this article, you can easily convert Excel files to PDFs for your needs.
ERROR: Could not find a version that satisfies the requirement pywin32 (from versions: none)
ERROR: No matching distribution found for pywin32
System: Mac
python 3.11
все работает, спасибо. было бы неплохо, если название файла можно было сделать переменной
Ala
Excelent !!! Subscribed.
What if I need to create a separate PDF file for each row in the Excel file?
Sir i got a error (-2147221005, 'Invalid class string', None, None)
Ok