Files
the_information_nexus/docs/tech_docs/python/python-docx.md

2.7 KiB

Reference guide for common use cases with the python-docx library:

python-docx Reference Guide

Installation

pip install python-docx

Creating and Saving Documents

from docx import Document

# Create a new document
doc = Document()

# Save the document
doc.save('path_to_file.docx')

Opening Existing Documents

doc = Document('path_to_existing_file.docx')

Adding Paragraphs

# Add a paragraph
paragraph = doc.add_paragraph('Your text here.')

# Add a paragraph with a predefined style
doc.add_paragraph('Styled text', style='Heading1')

Adding Headings

# Add a heading level 1
doc.add_heading('Heading Level 1', level=1)

# Add a heading level 2
doc.add_heading('Heading Level 2', level=2)

Working with Runs

# Add a run to an existing paragraph
run = paragraph.add_run(' Additional text')

# Apply bold and italic
run.bold = True
run.italic = True

Inserting Images

# Add an image
doc.add_picture('path_to_image.jpg', width=docx.shared.Inches(1), height=docx.shared.Cm(4))

Creating Tables

# Create a table with 2 rows and 2 columns
table = doc.add_table(rows=2, cols=2)

# Add data to cells
table.cell(0, 0).text = 'First cell'
table.cell(0, 1).text = 'Second cell'

Adding Lists

# Add a bulleted list
doc.add_paragraph('First item', style='ListBullet')
doc.add_paragraph('Second item', style='ListBullet')

# Add a numbered list
doc.add_paragraph('First item', style='ListNumber')
doc.add_paragraph('Second item', style='ListNumber')

Using Headers and Footers

# Access the header of the document
header = doc.sections[0].header
header.paragraphs[0].text = "Header text"

# Access the footer of the document
footer = doc.sections[0].footer
footer.paragraphs[0].text = "Footer text"

Applying Styles

# Apply a style to a paragraph
paragraph.style = 'Title'

# Apply a style to a run
run.style = 'QuoteChar'

Page Layout

# Change page orientation to landscape
section = doc.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE

# Set page width and height
section.page_width = docx.shared.Mm(297)
section.page_height = docx.shared.Mm(210)

Adding Footnotes and Endnotes

# Add a footnote
footnote = doc.add_footnote()
footnote.add_paragraph('Footnote text')

# Add an endnote
endnote = doc.add_endnote()
endnote.add_paragraph('Endnote text')
# Add a hyperlink
doc.add_paragraph().add_hyperlink('OpenAI', 'https://www.openai.com', 'Hyperlink')

Remember to save your document after making changes:

doc.save('path_to_file.docx')