Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have working on docx method in python. I want my key value pair in dictionary get extracted in word format directly. As there are 100 of key value pairs i want it get automatically extracted in word document as the format i want.

What I have tried:

import docx
mydoc = docx.Document()

price = {"Maling":["Melon Jam 300gram", "34aed"], "Nescafe":["3 in 1 coffee", "20 aed"]}

# defination to get value in word
  for i in price:
    mydoc.add_paragraph(i)
    for j in price[i]:
    mydoc.add_paragraph(j)
    mydoc.add_run.bold= True

    mydoc.save('demo.docx')

#I am excepting this kind of result like below:

 Maling
 Melon Jam 300gram
 34 Aed
Posted
Updated 8-Oct-20 21:46pm

1 solution

Would suggest you to go through the knowledgebase doc here: Working with Styles — python-docx 0.8.10 documentation[^]

Just add style to the add_paragraph as needed:
Python
paragraph = document.add_paragraph(style='Body Text')

Do notice, there are few defined styles that can be used right away:
Python
from docx.enum.style import WD_STYLE_TYPE
styles = document.styles
paragraph_styles = [
    s for s in styles if s.type == WD_STYLE_TYPE.PARAGRAPH
]
for style in paragraph_styles:
    print(style.name)

# Outputs
# Normal
# Body Text
# List Bullet
There are paragraph specific style properties that you can use to get desired feel. Try out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900