Welcome folks today in this blog post we will be using the openpyxl
library to export excel (.xlsx) file to pdf
document using reportlab
library in python. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries using the pip
command as shown below
pip install openpyxl
pip install reportlab
And after that you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import os from openpyxl import load_workbook from reportlab.lib.pagesizes import letter, landscape from reportlab.lib.units import inch from reportlab.pdfgen import canvas if __name__ == '__main__': # Set file paths excel_path = os.path.abspath('sample.xlsx') pdf_path = os.path.abspath('example.pdf') # Export Excel file to PDF excel_to_pdf(excel_path, pdf_path) |
As you can see we are importing the libraries
at the top and now we need to export the excel
file to pdf as shown below. As you can see we are passing the input
excel file which is called sample.xlsx
and then we are also providing the output pdf
file path which is example.pdf and then we are calling the custom function which is called excel_to_pdf()
method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
def excel_to_pdf(excel_path, pdf_path): # Load Excel workbook workbook = load_workbook(excel_path) # Select active sheet worksheet = workbook.active # Get dimensions of active sheet max_row = worksheet.max_row max_column = worksheet.max_column # Set PDF canvas c = canvas.Canvas(pdf_path, pagesize=landscape(letter)) # Set margins top_margin = 3*inch left_margin = 0.75*inch bottom_margin = 0.75*inch right_margin = 0.75*inch # Set cell width and height cell_width = (11*inch - left_margin - right_margin) / max_column cell_height = (8.5*inch - top_margin - bottom_margin) / max_row # Iterate over cells and add to PDF for row in range(1, max_row+1): for column in range(1, max_column+1): cell = worksheet.cell(row=row, column=column) text = str(cell.value) print(text) x = left_margin + (column-1)*cell_width y = 11*inch - (top_margin + row*cell_height) c.drawString(x, y, text) # Save PDF and close canvas c.save() |
As you can see we are getting all the column
and row cell values and then we are inserting it inside the pdf document. We are setting the margin
from all the sides in the pdf document.
Now if you execute the python
script you will see the below output
python app.py