Add docs/tech_docs/python/python-docx.md

This commit is contained in:
2024-03-28 17:10:45 +00:00
parent 2aa434a236
commit a4d2375719

View File

@@ -0,0 +1,132 @@
## Reference guide for common use cases with the `python-docx` library:
# `python-docx` Reference Guide
## Installation
```
pip install python-docx
```
## Creating and Saving Documents
```python
from docx import Document
# Create a new document
doc = Document()
# Save the document
doc.save('path_to_file.docx')
```
## Opening Existing Documents
```python
doc = Document('path_to_existing_file.docx')
```
## Adding Paragraphs
```python
# 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
```python
# 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
```python
# 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
```python
# Add an image
doc.add_picture('path_to_image.jpg', width=docx.shared.Inches(1), height=docx.shared.Cm(4))
```
## Creating Tables
```python
# 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
```python
# 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
```python
# 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
```python
# Apply a style to a paragraph
paragraph.style = 'Title'
# Apply a style to a run
run.style = 'QuoteChar'
```
## Page Layout
```python
# 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
```python
# Add a footnote
footnote = doc.add_footnote()
footnote.add_paragraph('Footnote text')
# Add an endnote
endnote = doc.add_endnote()
endnote.add_paragraph('Endnote text')
```
## Adding Bookmarks and Hyperlinks
```python
# Add a hyperlink
doc.add_paragraph().add_hyperlink('OpenAI', 'https://www.openai.com', 'Hyperlink')
```
Remember to save your document after making changes:
```python
doc.save('path_to_file.docx')
```