preface

In my recent work, I needed to visualize the data of a period of time queried and export it to Word format. As I am not familiar with Word operation, I have looked up the relevant documentation. Here is a brief record of how to use Python to operate Word.

instructions

  • This code is derived from the official documentation (python – docx. Readthedocs. IO/en/latest /), to code here

rendering

code

# coding:utf-8

"""Python operating on Word"""

from docx import Document
from docx.shared import Inches

Create word document object
document = Document()
# add title
document.add_heading('Document Title', 0)

# add paragraph
p = document.add_paragraph('A plain paragraph having some ')

# Add paragraph text and specify style: here set text to bold
p.add_run('bold').bold = True

Add paragraph text
p.add_run(' and some ')

Add paragraph text and specify style: set text to italic
p.add_run('italic.').italic = True

# add level 1 title
document.add_heading('Heading, level 1', level=1)

Add a paragraph and set the paragraph style
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'  # The style is a small dot
)
document.add_paragraph(
    'first item in ordered list', style='List Number'  # number
)

# Insert image :Inches indicates the unit of the image in Inches
document.add_picture('pic.jpg', width=Inches(3.0)) records = (3,'101'.'Spam'),
    (7, '422'.'Eggs'),
    (4, '631'.'Spam, spam, eggs, and spam'))Create a table with three columns in one row
table = document.add_table(rows=1, cols=3)
Get the number of columns in the first row
hdr_cells = table.rows[0].cells

Add content to each column of the first row
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'

Add new rows to table and add contents to each column
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

# add pagination
document.add_page_break()

Save the world document
document.save('demo.docx')

if __name__ == "__main__":
    pass

Copy the code

Like a like!!