cfabio

Word.py

Jan 18th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. #########################
  2. # Word docx
  3. #########################
  4. import docx
  5. doc = docx.Document(sFileName) #list of paragraphs
  6. paragraphs = doc.paragraphs
  7. paragraphs[0].text
  8. p = paragraphs[0]
  9.  
  10. #in each paragraph there are mltiple Runs (every style change is the start of a new Run)
  11. p.run[0].text
  12.  
  13. p.run[0].bold   #it can be True, False, or None. The attribute bold == Note for inherited the style from the paragraph
  14. p.run[0].italic
  15. r = p.run[0].underline
  16.  
  17. p.run[0].underline = True #change the attribute vale.  
  18.  
  19.  
  20. #each run and paragraph has a Style build in
  21. p.style
  22. r.style = "Title"
  23. d.save(sFileName)
  24.  
  25. ###write docx starting from empty doc###
  26. d = docx.Document()
  27. d.add_paragraph('Hello this is...')   #they can be added only at the end. If we want to add one in the middle of a doc we need to create
  28.                                       #a new document iterating the paragraphs of the current one, and dynamically adding the new paragraph
  29. d.paragraphs[0].add_run('This is a new run')
  30. p.runs[0].bold = True
  31. d.save(sFileName)
  32.  
  33. #print all the text in a document forgetting the style. Only put one paragraph after the other separated by the \n
  34. def getText(sFileName) :
  35.     doc = docx.Document(filename)
  36.     fullText = []
  37.     for p in doc.paragraphs :
  38.         fullText.append(p.text)
  39.     return '\n'.join(fullText)
  40.  
  41. print(getText(sFileNmae))
Advertisement
Add Comment
Please, Sign In to add comment