Python uses Python docx to create and modify the titles, paragraphs, and tables of Word documents
Preparation work for environmental construction:
1. Install Python: On the Python official website( https://www.python.org/ )Download the latest version of Python and follow the installation prompts to install it.
2. Install the Python docx library: Run 'pip install Python docx' from the command line to install the Python docx library.
Dependent class libraries:
-Python docx: A Python library for creating and modifying Microsoft Word documents.
The following is a complete example showing how to use Python docx to create and modify Word documents:
python
from docx import Document
from docx.shared import Pt
#Create a new Word document object
doc = Document()
#Set Document Title
title = doc.add_heading(level=0)
title.alignment = 1
run = title.add_run("My Document Title")
run.bold = True
run.font.size = Pt(18)
#Add paragraph
paragraph = doc.add_paragraph()
run = paragraph.add_run("This is a paragraph.")
#Add Table
table = doc.add_table(rows=3, cols=3)
Table. style="Table Grid" # Set Table Style
#Fill in Table Content
for i in range(3):
for j in range(3):
cell = table.cell(i, j)
cell.text = f"Row {i+1}, Col {j+1}"
#Save Document
doc.save("my_document.docx")
The above code first imports the 'Document' and 'Pt' classes, which are used to create and modify Word documents, and the 'Pt' class is used to set font size.
Then, we create a new Word document object 'doc' and set the document title using 'add'_ The 'heading' method creates a title, with 'level=0' representing the first level title. The 'alignment' attribute sets the title to be centered, the 'bold' attribute sets the title to bold, and the 'font. size' attribute sets the font size of the title.
Next, use 'add'_ The 'paragraph' method adds a paragraph using 'add'_ The 'run' method adds specific textual content.
Then, use 'add'_ The 'table' method adds a table, specifying the number of rows and columns in the table, and sets the table style using the 'style' attribute. Here, the 'Table Grid' style is selected.
Finally, use two nested 'for' loops to traverse all cells in the table, and use the 'cell. text' attribute to set the text content of the cells.
Finally, use the 'save' method to save the document and specify the saved file name.
Summary:
The Python docx library makes it easy to create and modify Microsoft Word documents. By using the 'Document' class, 'Heading' class, 'Paragraph' class, and 'Table' class, you can create and modify document titles, paragraphs, and tables.