Tuesday, June 21, 2022

Create & format MS-Word file in Python

# Create & format MS-Word file in Python

# https://www.youtube.com/watch?v=so2illANiRw


from docx import Document


doc = Document()

doc.add_heading("Hello World", 0)

doc.add_heading("Hello World")

doc.add_heading("Hello World", 2)

doc.add_heading("Hello World", 6)


p = doc.add_paragraph("Sample text")

p.add_run(" This text is bold.").bold = True

p.add_run(" This text is italicised.").italic = True


doc.add_paragraph("Item 1", style="List Bullet")

doc.add_paragraph("Item 2", style="List Bullet")

doc.add_paragraph("Item 3", style="List Bullet")


table_header = ["Name", "Age", "Job"]

data = [["John", 46, "Programmer"],

        ["Mary", 55, "Programmer"],

        ["Anna", 27, "Accountant"],

        ["Bob",  46, "Chef"]

       ]

table = doc.add_table(rows=1, cols=3)

for i in range(3):

  table.rows[0].cells[i].text = table_header[i]


for name, age, job in data:

  cells = table.add_row().cells

  cells[0].text = name

  cells[1].text = str(age)

  cells[2].text = job


doc.add_page_break()

doc.add_paragraph("Hello new page")

doc.add_picture("Thejus.png")


doc.save("Test.docx")

No comments:

Post a Comment