Search code examples
pythonpython-3.xlistdocxreceipt

Looking to create a word document from code in Python


I have this code:

import random
from docx import Document
from docx.shared import Inches 
title = "seans store"
"""
Declare the two dictionaries with name stock and prices
"""
stock = {
    "banana": 60,
    "apple": 150,
    "orange": 120,
    "pear": 150,
    "tomatoes": 120,
    "yoghurt": 100
}

prices = {
    "yoghurt": 1,
    "banana": 2,
    "apple": 1,
    "orange": .5,
    "pear": 1.5,
    "tomatoes": 1.1
}
"""
Declare the items within the customers shopping cart
"""
shopping_cart = [("pear",1), ("orange", 1), ("apple",2), ("tomatoes",2), ("yoghurt",0)]
for i in shopping_cart:
    if stock[i[0]] - i[1] < 0:
        shopping_cart.pop(shopping_cart.index(i))
    else:
        stock[i[0]] -= i[1]
print(f"Thank you for shopping @ {title.title()}")
for x in range(1):
    Order_number = random.randint(100,999)
total_items = sum([i[1] for i in shopping_cart])
print(f"Your Order number is: {Order_number}")
print(f"Total items bought: {total_items}")
print("----------------")
print("     Bill")
print("----------------")
for i in shopping_cart:
    print(f"{i[0]} x{i[1]} @  £{prices[i[0]]}")
total = (sum([prices[i[0]] * i[1]  for i in shopping_cart]))
total_after_tax = total + (total*0.2)
tax_total = total_after_tax - total
print("----------------")
print("VAT @: £{:.2f}".format(tax_total))
print("----------------")
print("Total is £{:.2f}".format(total_after_tax))
"""Reciept creation"""
document = Document()
document.add_heading(f'Reciept for {title.title()}', 0)
p = document.add_paragraph('Items Ordered: ')

document.save("Reciept.docx")

and I want to create a document from this that lists the items the customer has ordered and their prices as a receipt. I am hoping to create this so I can automate receipt creation processes in the future. I am also curious if it is possible to get the code to automatically print or open the word document software when the code is finished.


Solution

  • If I understand it correctly - you intend to output the print statements to the word document. The only way you can do that is by adding an .add_paragraph() method via the docx library.

    A good example from the documentaiton

    from docx import Document
    from docx.shared import Inches
    
    document = Document()
    
    document.add_heading('Document Title', 0)
    
    p = document.add_paragraph('A plain paragraph having some ')
    p.add_run('bold').bold = True
    p.add_run(' and some ')
    p.add_run('italic.').italic = True
    
    document.add_heading('Heading, level 1', level=1)
    document.add_paragraph('Intense quote', style='Intense Quote')
    
    document.add_paragraph(
        'first item in unordered list', style='List Bullet'
    )
    document.add_paragraph(
        'first item in ordered list', style='List Number'
    )
    
    document.add_picture('monty-truth.png', width=Inches(1.25))
    
    document.add_page_break()
    
    document.save('demo.docx')
    

    Once you save the file, you can open it by simply opening the file in the standard way using the os module. This will default to whatever application you have set to open files of type .docx type.

    import os
    os.startfile('C:\\Path\\To\\demo.docx')