Word of office automation in python (Part 1)

AirPython 2020-11-12 22:00:32
word office automation python


image

1. Preface

In the daily automation office , Use Python You can really get twice the result with half the effort !

In the previous series , We are right.  Python operation Excel A comprehensive summary was made

The most comprehensive summary | Chat Python Office automation Excel( On )

The most comprehensive summary | Chat Python Office automation Excel( in )

The most comprehensive summary | Chat Python Office automation Excel( Next )

Start with this article , Let's move on to another common document format :Word

2. Get ready

Python operation Word The most common dependency libraries are :python-docx

therefore , Before starting the operation , We need to install this dependency Library in a virtual environment

#  Installation dependency
pip3 install python-docx

3. Write down the actual combat

We need to know a Word The page structure of the document

They are :

  • file - Document

  • chapter - Section

  • The paragraph - Paragraph

  • Text block - Run

Frequently operated data types include : The paragraph 、 title 、 list 、 picture 、 form 、 style

First , Use  Document  Create a document object , It's equivalent to creating a blank document

from docx import Document
# 1、 Create a new blank document
doc = Document()

then , You can write data to the document

Using document objects  add_heading(text,level)  Method can write the title

among , The first 1 Parameters are the title content , The first 2 Parameters represent the level of the title

such as : Write the first level title separately 、 Secondary title 、 Three level title

# 2、 The new content
# 2.1 title
# Write a first level Title respectively , A secondary title , A three-level title
doc.add_heading(' First level title ', 0)
doc.add_heading(' Secondary title ', 1)
doc.add_heading(' Three level title ', 2)

The paragraph Paragraph contain 3 class , Namely :

  • Ordinary paragraphs

  • Custom style paragraph

  • Quote paragraph

By default , Using document objects  add_paragraph(text,style)  Method to add a paragraph

Ordinary paragraphs : If the second parameter style There was no introduction , It means to add a normal paragraph

Quote paragraph : For quoted paragraphs , Just specify the paragraph style as  Intense Quote  that will do

# 2.2.1 New normal paragraph
doc.add_paragraph(" I am a normal paragraph .")
# 2.2.3 Add a quote paragraph
# Just specify the style as :Intense Quote
doc.add_paragraph('-- I'm a quotation paragraph --', style='Intense Quote')

Custom style paragraph : Here you are 2 Type of implementation

Namely :

  • Create an empty paragraph object , Add text blocks Run When , Also specify the font style

  • Create a new style using document objects ( Or patterns that already exist ), And then when you add a paragraph , Set to the second parameter

Considering the reusability of styles , The first 2 It may be more practical

The corresponding method is :

document.styles.add_style(style_name,type)

By the end of 2 For example , Add a custom style paragraph , Set the font name of the paragraph 、 size 、 Color 、 Is it bold 、 Alignment, etc

PS: The first 1 Type of implementation , At the end of the article, the source code will provide

This method is first 2 Parameters are used to specify the style type , contain 3 Kind of

The corresponding relations are as follows :

  • 1: paragraph style

  • 2: Character style

  • 3: Table style

def create_style(document, style_name, style_type, font_size=-1, font_color=None, font_name=None, align=None):
"""
Create a style
:param align:
:param document:
:param style_name: Style name
:param style_type: Style type ,1: paragraph style , 2: Character style , 3: Table style
:param font_name:
:param font_color:
:param font_size:
:return:
"""
if font_color is None:
font_color = []
# Be careful : You have to judge whether a style exists , Otherwise, adding again will report an error
style_names = [style.name for style in document.styles]
if style_name in style_names:
# print(' Patterns already exist , There is no need to re add !')
return
font_style = document.styles.add_style(style_name, style_type)
# font size
if font_size != -1:
font_style.font.size = Pt(font_size)
# The font color
# such as :[0xff,0x00,0x00]
if font_color and len(font_color) == 3:
font_style.font.color.rgb = RGBColor(font_color[0], font_color[1], font_color[2])
# Alignment mode
# Be careful : The paragraph 、 Tables have alignment
if style_type != 2 and align:
font_style.paragraph_format.alignment = align
# font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
# font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# Chinese font name
if font_name:
font_style.font.name = font_name
font_style._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
return font_style

It should be noted that , When a new style is added , You must first determine whether the style name exists , Otherwise, an error will be reported

Last , When you add a paragraph , Pass in the style created above to 2 Of the parameters

Use add_paragraph() Method to add a paragraph , The return value is a paragraph object

image

This object can also use  add_run(text,style)  Method , Add a block of text after a paragraph Run  And specify the style

# 1/ paragraph style
style_paragraph = create_style(document=doc, style_name="style2", style_type=1, font_size=30,
font_color=[0xff, 0x00, 0x00])
# 2/ Character style
style_string = create_style(document=doc, style_name="style3", style_type=2, font_size=15,
font_color=[0x00, 0xff, 0x00])
# 3/ Table style
# The alignment is : In the middle
style_table = create_style(document=doc, style_name="style4", style_type=3, font_size=25,
font_color=[0x00, 0x00, 0xff], align=WD_PARAGRAPH_ALIGNMENT.CENTER)
current_paragraph = doc.add_paragraph(" I am a paragraph with its own style ( Mode two )!!!", style_paragraph)
# Character style
current_paragraph.add_run("【 The paragraph 2 Part of the characters in 】", style_string)

Word In the document , Ordered lists and unordered lists are also commonly used

in fact , It's similar to adding a paragraph , Adding lists also uses document objects add_paragraph()  Method , Specify different styles style To add

among ,

  • Ordered list :List Number

  • Unordered list :List Bullet

def add_list(document, data, isorder):
"""
Add list data to unordered list / In an ordered list
:param document: Document object
:param data: The list of data
:param isorder: Is there a sequence table
:return:
"""
# Unordered list
if not isorder:
for item in data:
document.add_paragraph(item, style='List Bullet')
else:
# Ordered list
for item in data:
document.add_paragraph(item, style='List Number')
# 2.3 list
# 2.3.1 Unordered list
add_list(doc, [" disorder -Item1", " disorder -Item2", " disorder -Item3"], False)
# 2.3.2 Ordered list
add_list(doc, [" Orderly -Item1", " Orderly -Item2", " Orderly -Item3"], True)

Next , Let's look at how to insert images into a document

Usage method :

add_picture(image,widht,height)

among ,

  • The first 1 Parameters represent the image path or image stream ( Network picture )

  • The first 2、3 Parameters are used to set the width of the picture 、 high

It should be noted that , If the width and height are not specified explicitly , It is shown in the original size of the picture ; If only one of them is set , Then the display will be scaled proportionally according to one of the settings

Writing local images is easy

def add_local_image(doc, image_path, width=None, height=None):
"""
Add local images to Word In the document
:param doc:
:param image_path:
:param width:
:param height:
:return:
"""
doc.add_picture(image_path, width=None if width is None else Inches(width),
height=None if height is None else Inches(height))
# 2.4.1 Insert local image
add_local_image(doc, './1.png', width=2)

For Web Images , We need to go through the Internet image address first , Get picture byte stream , Pass in to the first parameter

import ssl
from io import BytesIO
def get_image_data_from_network(url):
"""
Get network picture byte stream
:param url: Picture address
:return:
"""
ssl._create_default_https_context = ssl._create_unverified_context
# Get the byte stream of network picture
image_data = BytesIO(urlopen(url).read())
return image_data
def add_network_image(doc, image_url, width=None, height=None):
"""
Add local images to Word In the document
:param doc:
:param image_url:
:param width:
:param height:
:return:
"""
# Get a picture stream
image_data = get_image_data_from_network(image_url)
doc.add_picture(image_data, width=None if width is None else Inches(width),
height=None if height is None else Inches(height))
# 2.4.2 Insert network picture
url = ' picture URL Address '
add_network_image(doc, url, width=3)

Last , Let's look at how to insert a table into a document

Usage method :

add_table(row_num,column_num,style=None)

Return value : Table objects  <class 'docx.table.Table'>

among ,

  • The first 1 Parameters : The number of rows in the table

  • The first 2 Parameters : The number of columns in the table

  • The first 3  Parameters : The style of the table

Use line / Column index , You can get a row in the table / A list of all cell objects

# Add one table form
table = doc.add_table(***)
# By line / Column index , Get a line / All cell objects of the column
# The first row is a list of all cell objects
head_cells = table.rows[0].cells

in addition , Table objects use  add_row()、add_column()  Method can add a line / Column

To specify the header 、 Table data , For example, insert a table

def add_table(doc, head_datas, datas, style=None):
"""
Add a table
:param doc:
:param head_datas: Header
:param datas: data
:param style:
:return:
"""
# Add a table
# A complete collection of all forms of tables :https://blog.csdn.net/ibiao/article/details/78595295
# The default style is :Table Grid
table = doc.add_table(rows=1, cols=len(head_datas), style=("Table Grid" if style is None else style))
# The first row is a list of all cell objects
head_cells = table.rows[0].cells
# Write data to the header
for index, head_item in enumerate(head_datas):
head_cells[index].text = head_item
# Traverse data and write data
for data in datas:
# Add a single row or column :add_row、add_column
row_cells = table.add_row().cells
for index, cell in enumerate(row_cells):
cell.text = str(data[index])
# 2.5 form
head_datas = [" full name ", " Age ", " region "]
datas = (
(' Zhang San ', 18, ' Shenzhen '),
(' Li Si ', 28, ' Beijing '),
(' Wang Wu ', 33, ' Shanghai '),
(' Sun Liu ', 42, ' Guangzhou ')
)
# Add a table , And specify the style
# add_table(doc, head_datas, datas, style_table)
add_table(doc, head_datas, datas)

It's important to point out that , The default style of the table is  Table Grid, You can also use the above method to customize a table style , Insert the table and set it in at the same time

4. Last

This article is about Word The routine operation of writing data has been comprehensively combed , More features include : Read 、 modify 、 lookup 、 Delete and other actual combat content will continue to output

To get all the source code , Official account 「 AirPython 」, The background to reply 「 word 」 You can get all the source code

If you think the article is good , Please   give the thumbs-up 、 Share 、 Leaving a message. Next , Because this will be the strongest driving force for me to continue to output more quality articles !

Recommended reading

The most comprehensive summary | Chat Python Office automation Excel( On )

The most comprehensive summary | Chat Python Office automation Excel( in )

The most comprehensive summary | Chat Python Office automation Excel( Next )

版权声明
本文为[AirPython]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database