How to Create PDF Invoices From Excel in Bulk With Python
To create invoices from Excel in bulk, keep your order lines in one Excel table, group the rows by invoice number with pandas, and draw one PDF per group with ReportLab. The free xlwings Lite add-in runs that Python code inside Excel, so one button turns 139 order lines into 20 finished PDF invoices, with no Python installation on your PC.
Table of contents
How it works
You read the order table into Python, split it into one small table per invoice number, and write each small table into its own PDF file. The order data stays in Excel. Python only does the repetitive part: layout, totals and saving 20 files instead of one.
The usual manual route is to copy the data into Word, run a mail merge, and export the PDFs one by one. That works for letters, where one row is one document. It gets awkward for invoices, where one invoice has a different number of line items than the next.
The demo workbook starts from a plain Excel table with 139 order lines. One click on a Create Invoices button writes 20 PDF invoices in about two seconds. Each invoice has the logo, the sender details, the customer address, the line items, a total and the payment terms.

This is the invoice the script in this post produces from the demo workbook. Everything on it comes from the workbook: the four sender cells, the customer columns and the order lines.
What you need
You need Excel (Microsoft 365 or Office 2021 and newer, on Windows, Mac or in the browser), the free xlwings Lite add-in, and two Python packages: pandas for the table and ReportLab for the PDF. You do not install Python itself. xlwings Lite brings its own.
| Part | What it does here |
|---|---|
| xlwings Lite | Adds a Python editor to Excel and turns a Python function into a button |
| pandas | Reads the Excel table, calculates the line totals and groups the rows per invoice |
| ReportLab | Draws each PDF: letterhead, address block, item table, total, page breaks |
| pathlib | Builds the file paths. It is part of Python, so nothing to install |
To install the add-in, go to Home, then Add-ins, then More Add-ins. Search the Office add-in store for xlwings Lite, click Add and then Continue. A task pane opens with a code editor. The built-in seaborn sample is a quick way to check that Python runs. If you have never used the add-in, my overview of running Python in Excel with xlwings Lite covers what it can and cannot do.
Set up the workbook
Use two sheets. A Company sheet holds the sender details in four cells, and an Orders sheet holds every invoice line in a proper Excel table. Keep one row per line item and repeat the invoice number on each row of the same invoice.
The Company sheet has the company name, address, email and payment terms in cells B4 to B7. Because the script reads these cells, a new address or new payment terms are a cell edit, not a code change.
The Orders sheet holds a table named tblOrders with these columns:
| Column | Example | Used for |
|---|---|---|
| InvoiceNo | INV-1001 | Grouping: one PDF per invoice number |
| Date | 03.07.2026 | Invoice date in the header |
| CustomerName, CustomerAddress, City, Country | Alpine Office Solutions AG | Bill-to block, read from the first row of each invoice |
| Product | Logo Design | Item description |
| Quantity, UnitPrice | 2, 420 | Line total and invoice total |
An Excel table matters here. When you paste more orders below it, the table grows and the script picks up the new rows on the next run. A fixed range like A1:I140 would silently miss them.
PDF invoice generator workbook
The demo workbook with the Company sheet, 139 fictional order lines in tblOrders and the complete Python code already inside xlwings Lite. Open it, click Create Invoices, get 20 PDFs.
Create the invoices step by step
Add ReportLab to the requirements, read the company cells and the order table, group the orders by invoice number, and hand each group to a function that draws the PDF. Then click the button and download the files. The code below is the complete script from the demo workbook.
-
Add ReportLab to the requirements. Open the requirements.txt tab in xlwings Lite and add
reportlabon its own line. pandas is already there for the samples. You can delete matplotlib and seaborn, which only the samples need. Every change to this tab needs a restart of the add-in, so click Restart in the yellow bar.
-
Import the libraries and set the paths. Paste this at the top of main.py.
OUTPUT_DIRis where the PDFs go,LOGO_FILEis your logo. Both sit in/data, the add-in’s own file storage.from html import escape from pathlib import Path import pandas as pd import xlwings as xw from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import mm from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle from xlwings import script # Where the finished PDFs land. /data is xlwings Lite's own folder and it # keeps whatever you write there. On Windows you can connect a real folder # instead (Files > Local Folders) and point this at it. OUTPUT_DIR = Path("/data/invoices") # Your logo. Drag the "assets" folder into Files > Import/Export and it # lands here. Swap in your own PNG and every invoice picks it up. LOGO_FILE = Path("/data/assets/logo.png") TABLE_NAME = "tblOrders" -
Read the company cells and the order table. The
@scriptdecorator turns the function into the green Create Invoices button. The function must take the workbook as itsbookparameter, which is how it reaches the sheets.parse_datesturns Excel date serial numbers back into real dates. Then one line computes every line total, andgroupbyhands back one small table per invoice number.@script(name="Create Invoices") def create_invoices(book: xw.Book): # make the folder first, so the PDFs have somewhere to go OUTPUT_DIR.mkdir(parents=True, exist_ok=True) # the four yellow cells on the Company sheet - they go on every invoice company_sheet = book.sheets["Company"] company = { "name": company_sheet["B4"].value, "address": company_sheet["B5"].value, "email": company_sheet["B6"].value, "terms": company_sheet["B7"].value, } print("Reading the order table...") orders = ( book.sheets["Orders"] .tables[TABLE_NAME] # parse_dates matters here: Excel hands a date over as a plain # number (Jan 1 2025 arrives as 45658), and this turns it back # into a real date. .range.options(pd.DataFrame, index=False, parse_dates=["Date"]) .value ) # quantity times price for every row at once - the same as dragging a # formula down the whole column, but in one line orders["LineTotal"] = orders["Quantity"] * orders["UnitPrice"] # groupby hands us the big table split into one small table per invoice # number - like filtering the list once per customer, except we get all # the pieces back in a single loop for invoice_no, items in orders.groupby("InvoiceNo"): draw_invoice(invoice_no, items, company) print(f"{invoice_no}: {len(items)} line items -> {invoice_no}.pdf") print(f"DONE. {orders['InvoiceNo'].nunique()} invoices written to /data/invoices.")Run it once before the PDF part exists and print the groups. You should see each invoice number with its number of line items, which is a cheap check that the grouping is right.
Reading the order table... INV-1001: 3 line items -> INV-1001.pdf INV-1002: 4 line items -> INV-1002.pdf INV-1003: 2 line items -> INV-1003.pdf INV-1004: 3 line items -> INV-1004.pdf INV-1005: 4 line items -> INV-1005.pdf INV-1006: 3 line items -> INV-1006.pdf INV-1007: 2 line items -> INV-1007.pdf INV-1008: 4 line items -> INV-1008.pdf INV-1009: 3 line items -> INV-1009.pdf INV-1010: 5 line items -> INV-1010.pdf INV-1011: 2 line items -> INV-1011.pdf INV-1012: 3 line items -> INV-1012.pdf INV-1013: 4 line items -> INV-1013.pdf INV-1014: 3 line items -> INV-1014.pdf INV-1015: 2 line items -> INV-1015.pdf INV-1016: 5 line items -> INV-1016.pdf INV-1017: 3 line items -> INV-1017.pdf INV-1018: 6 line items -> INV-1018.pdf INV-1019: 33 line items -> INV-1019.pdf INV-1020: 45 line items -> INV-1020.pdf -
Draw each invoice with ReportLab. This part builds the PDF.
letterheadpaints the logo, the invoice number, the date, the sender block and the payment terms on every page.items_tablebuilds the item table with a blue header row and a bold total row. I asked AI to help with this layout code, and you can change colors, column widths and fonts in the constants at the top. One small change from the video: the bill-to lines are separate paragraphs and go throughescape(), so special characters in a cell cannot break the PDF.# --- everything below here draws the PDF --- # ReportLab measures in points, so we write "10 * mm" and it converts BLUE = colors.HexColor("#3772A3") # header row + the line above TOTAL GRAY = colors.HexColor("#646464") # payment terms footer MARGIN = 10 * mm LOGO_WIDTH = 46 * mm LOGO_HEIGHT = 9.7 * mm # the logo is about 4.7x wider than tall COL_WIDTHS = [95 * mm, 20 * mm, 35 * mm, 40 * mm] COL_HEADERS = ["Product", "Qty", "Unit Price", "Line Total"] # how the text in the address block looks BODY = ParagraphStyle("Body", fontName="Helvetica", fontSize=10, leading=15) BOLD = ParagraphStyle("Bold", parent=BODY, fontName="Helvetica-Bold") def draw_invoice(invoice_no, items, company): # every line of one invoice has the same customer and date, so we just # read them off the first row first = items.iloc[0] # the page setup. The top margin is deep because the letterhead gets # painted into that empty strip further down. doc = SimpleDocTemplate( str(OUTPUT_DIR / f"{invoice_no}.pdf"), pagesize=A4, leftMargin=MARGIN, rightMargin=MARGIN, topMargin=52 * mm, bottomMargin=25 * mm, title=f"Invoice {invoice_no}", author=company["name"], ) # the address block: a bold heading, then one line per value. # escape() keeps a stray & or angle bracket in a cell from breaking the PDF bill_to = [Paragraph("Bill To:", BOLD)] + [ Paragraph(escape(str(text), quote=False), BODY) for text in (first["CustomerName"], first["CustomerAddress"], f"{first['City']}, {first['Country']}") ] # ReportLab runs this once for every page it makes and hands us a pen # to draw with. That is why page 2 gets the letterhead as well. def letterhead(canvas, doc): top = A4[1] - 20 * mm # mask="auto" keeps the see-through parts of the PNG see-through. # The check means the script still runs before you add your logo. if LOGO_FILE.exists(): canvas.drawImage(str(LOGO_FILE), MARGIN, top - LOGO_HEIGHT + 4 * mm, width=LOGO_WIDTH, height=LOGO_HEIGHT, mask="auto") canvas.setFont("Helvetica-Bold", 16) canvas.drawRightString(A4[0] - MARGIN, top, f"INVOICE {invoice_no}") canvas.setFont("Helvetica", 10) canvas.drawRightString(A4[0] - MARGIN, top - 8 * mm, f"Date: {first['Date']:%d.%m.%Y}") canvas.drawString(MARGIN, top - 12 * mm, company["name"]) canvas.drawString(MARGIN, top - 17 * mm, company["address"]) canvas.drawString(MARGIN, top - 22 * mm, company["email"]) canvas.setFont("Helvetica-Oblique", 9) canvas.setFillColor(GRAY) canvas.drawString(MARGIN, 15 * mm, company["terms"]) # we hand over the blocks in order and ReportLab works out where the # page ends - that is the whole trick doc.build([*bill_to, Spacer(1, 8 * mm), items_table(items)], onFirstPage=letterhead, onLaterPages=letterhead) def items_table(items): # the table as a plain list of rows: headers, one row per item, then TOTAL rows = [COL_HEADERS] rows += [ [row.Product, f"{row.Quantity:.0f}", f"{row.UnitPrice:,.2f}", f"{row.LineTotal:,.2f}"] for row in items.itertuples() ] rows.append(["", "", "TOTAL", f"EUR {items['LineTotal'].sum():,.2f}"]) # if the items spill onto page 2, print the header row up there again table = Table(rows, colWidths=COL_WIDTHS, repeatRows=1) # The formatting, one rule per line: what to change, then which cells - # given as first cell and last cell, like selecting a range in Excel. # (0, 0) is the top-left cell and -1 means "the last one". table.setStyle(TableStyle([ ("BACKGROUND", (0, 0), (-1, 0), BLUE), # blue header row ("TEXTCOLOR", (0, 0), (-1, 0), colors.white), ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), ("FONTNAME", (0, -1), (-1, -1), "Helvetica-Bold"), # bold TOTAL row ("FONTSIZE", (0, 0), (-1, -1), 10), ("ALIGN", (1, 0), (-1, -1), "RIGHT"), # all number columns ("TOPPADDING", (0, 0), (-1, -1), 5), ("BOTTOMPADDING", (0, 0), (-1, -1), 5), ("LINEBELOW", (0, 1), (-1, -2), 0.25, colors.HexColor("#CCCCCC")), ("LINEABOVE", (0, -1), (-1, -1), 1, BLUE), ])) return table -
Add your logo. Open the xlwings Lite menu, go to Files, and drag a folder called
assetswith yourlogo.pnginto the Import/Export area. It lands at/data/assets/logo.png. The script checks that the file exists, so it still runs without a logo. -
Click Create Invoices and download the PDFs. The output pane lists every invoice and ends with a DONE line. Go back to Files to see the PDFs under
/data/invoices. Each row has a download button, and Download All gets everything at once.
The Company sheet and the button look like this while you build it. The yellow cells feed the dictionary in step 3, so the first run prints exactly what you typed there.


Invoices longer than one page
ReportLab moves the extra rows to a new page by itself. The letterhead function runs on every page, and the item table repeats its blue header row, so page two still has the logo, the invoice number and the column titles. The total lands after the last line item.
In the demo, INV-1019 has 33 line items and INV-1020 has 45. Both run onto a second page without any extra code. The two settings that make this work are onLaterPages=letterhead in doc.build and repeatRows=1 on the table.

This is the part that hurts most in Word. A mail merge template has a fixed shape, so a 45-line invoice either overflows or needs a workaround.
Save the PDFs to a folder on your PC
On Windows you can mount a local folder in xlwings Lite and write the PDFs there instead of the add-in’s storage. The files then land directly in your project folder, a synced folder or any place you pick.
- Create a folder on your PC, for example
outputs. - In the xlwings Lite menu, open Files and switch to the Local Folders tab.
- Click Add Folder, pick the folder, and confirm the two browser prompts that let xlwings Lite read and write it.
- Change one line in the script:
OUTPUT_DIR = Path("/outputs/invoices"). - Click Create Invoices again. An invoices folder with all PDFs appears inside your folder.

Files in /data are deleted when the Office cache is cleared, as the Files panel itself warns. If you keep the PDFs, download them or use a local folder.
Share the workbook
Send the workbook like any other .xlsx file. The Python code is stored inside it, so a colleague only needs the xlwings Lite add-in. Turn on App Mode in the xlwings Lite settings and they see only the green Create Invoices button, not the code.
The workbook stays a normal .xlsx. There are no macros and no .xlsm, so it does not trigger the macro warning that VBA files do. Your colleague edits the Company cells or pastes new orders into the table and clicks the button.
Word mail merge, ExcelToWord or Python
Use Word mail merge for simple letters where one row is one document. Use a template tool when people need to edit the layout in Word. Use Python when one document holds many rows, like invoices with line items, or when you want full control over the PDF.
| Word mail merge | ExcelToWord | Python with ReportLab | |
|---|---|---|---|
| Layout lives in | A Word document | A Word template with placeholders | Python code |
| One document per | Row | Row | Whatever you group by |
| Varying number of line items | Hard | Via an Excel range per row | Built in (groupby) |
| Separate PDF files | Extra steps | Yes, Word, PDF or both | Yes |
| Coding | None | None | Yes, with AI help |
If you prefer a Word template and no code, I built ExcelToWord for documents from Excel data. If you like Python but want Word files people can still edit, my docxtpl tutorial fills a Word template from Python, and this post generates Word documents in bulk from an Excel list.
Troubleshooting
Most failures come from four things: ReportLab not installed yet, a table or sheet name that does not match the code, dates that arrive as numbers, and special characters in a cell. Each one shows a clear message in the output pane.
- ModuleNotFoundError: No module named ‘reportlab’. Add
reportlabto requirements.txt and restart the add-in. Saving the tab alone is not enough. - KeyError or a missing table. The names in the code must match the workbook exactly: the sheets Company and Orders and the table
tblOrders. Check the table name under Table Design, then Table Name. - The date shows up as a number like 46206. Keep
parse_dates=["Date"]in the options call. Excel stores dates as serial numbers. - A customer name with angle brackets breaks the PDF. ReportLab reads paragraph text as light markup, so a name like “Smith <Retail>” raises a parse error. The script above already runs every bill-to value through
escape()from Python’s html module. Keep that if you add more fields to a Paragraph. - No logo on the invoice. The script skips the logo quietly when the file is missing. Check that Files shows
/data/assets/logo.pngwith exactly that name. - The PDFs are gone the next day. Files in
/datado not survive a cleared Office cache. Download them or write to a local folder.
Other documents from the same pattern
Anything where one table becomes one document per group: quotes, order confirmations, delivery notes, certificates, customer statements or a monthly report per region. Change the grouping column and the layout, and keep the rest of the script.
Two natural next steps are sending each PDF to its customer and combining PDFs. For the sending part, see how I create files and send them through Outlook with Python, or use a mail merge from Excel to Outlook or Gmail that attaches each customer’s own PDF without code. For combining, I have a post on merging PDF files from Excel. And if your data is better shown on screen than on paper, the same xlwings Lite setup can turn an Excel table into an interactive dashboard.
Once the invoices are out, a Python payment reminder script can email the customers whose invoices are still unpaid.
Learn the Python behind this invoice generator the way an Excel user thinks, from a VLOOKUP in pandas to a finished one-click automation built with xlwings Lite, and then let AI write the layout code with you.
