Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of word documents operated by Python

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Python operation word document example analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Write at the front

Python-docx does not support doc documents, so be sure to pay attention to this. If you use doc documents, you need to convert them to docx format with Word-related software in advance. There is a fundamental difference between doc and docx, one in binary and the other in XML format.

Installation pip install python-docx of the module.

The following URL is ready first.

Official manual: https://python-docx.readthedocs.io/en/latest/index.html

Pypi official address: https://pypi.org/project/python-docx/

When the data is ready, you can enter the coding process.

Create a document

The first requirement is to create a document and write all kinds of information in it.

To implement the first step, write a title

Note the use of the add_heading () function below.

Creating a Document object by from docx import Document# is equivalent to opening a Word document document = Document () # adding a title document.add_heading ('this is a title', level=0) in the Word document on your computer # saving the document document.save ('demo.docx') adding text paragraphs

Note that the add_paragraph () function adds paragraphs and appends text using add_run () below

From docx import Document# creating a Document object is equivalent to opening a Word document document = Document () # adding a title document.add_heading ('this is a title', level=0) # adding a paragraph in the Word document p = paragraph ('this is a blank paragraph') # adding styled text # adding a paragraph Text can contain # add_run () such as tabs (\ t), newline characters (\ n), or carriage returns (\ r) to add text p.add_run ('\ nI tilted') after a paragraph. Italic = True # add a slanted text p.add_run ('\ nI bold'). Bold = True # add a bold text # Save document document.save ('demo.docx')

Add text before the paragraph

P.add_run ('\ nI tilted'). Italic = True # add a slanted text p.add_run ('\ nI bold'). Bold = True # add a bold text # insert content prep_p = p.insert_paragraph_before before the paragraph ('insert content before paragraph')

Paragraphs can also add page breaks, as shown in the following code:

# insert content before a paragraph prep_p = p.insert_paragraph_before ('insert content before paragraph') document.add_page_break () p1 = document.add_paragraph ('new page new paragraph')

Addition of list

Addition of unordered list

# add list (previous dot) document.add_paragraph ('I have a dot in front', style='List Bullet') # add list (previous dot) document.add_paragraph ('second dot', style='List Bullet')

Addition of ordered list

# add list (previous number) document.add_paragraph ('I have a number in front of me', style='List Number') # add list (previous number) add document.add_paragraph ('second number', style='List Number') picture

The methods available for the Document object are as follows:

Add_heading (self, text='', level=1): add title

Add_page_break (self): page break

Add_paragraph (self, text='', style=None): adding paragraphs

Add_picture (self, image_path_or_stream, width=None, height=None): add pictures

Add_section (self, start_type=2): add sections

Add_table (self, rows, cols, style=None): add tables

This section focuses on the add_picture () method.

Document.add_picture (r ".. / 9.png", width=Inches (1))

The parameter image_path_or_stream in the add_picture () function can be a relative address or an absolute address, or a picture data stream. In the above code, Inches represents inches. In addition, python-docx also provides centimeters (Cm), such as setting 1cm: Cm (1). You need to import from docx.shared import Inches and Cm in advance when you use it.

Table addition

Using the add_table () function, you can add a table to an Word document.

P1 = document.add_paragraph ('new page new paragraph') # add a 2 × 2 table table = document.add_table (rows=2, cols=2) # get row 1, column 2 cell cell = table.cell (0,1) # set cell text cell.text = 'row 1, column 2' # get row 2 row = table.rows [1] row.cells [0] .text = 'eraser' row.cells [1] .text = 'metaphor'

When you study, pay attention to the relevant notes, you can master this part of the content.

Related style settin

Formatting requires add_run (), and paragraphs generated using add_paragraph () directly cannot be styled directly, such as fonts.

# Import of module from docx.shared import Pt, Cm, Inchesfrom docx.oxml.ns import qnfrom docx.enum.text import WD_ALIGN_PARAGRAPHfrom docx.shared import RGBColor# first level title level=0head0 = document.add_heading (level=0) # title center head0.alignment = WD_ALIGN_PARAGRAPH.CENTERtitle_run = head0.add_run ('this is a center title' ) title_run.font.size = Pt (24) # title English font title_run.font.name = 'Times New Roman'# title Chinese font title_run.element.rPr.rFonts.set (qn (' wtitle_run.font.name EastAsia'), 'Microsoft Yahei') # font color title_run.font.color.rgb = RGBColor (4,60,169)

Where the WD_ALIGN_PARAGRAPH object represents how the paragraph treats it, and its values include the following

WD_ALIGN_PARAGRAPH. LEFT: align to the left

WD_ALIGN_PARAGRAPH. CENTER: centered on it

WD_ALIGN_PARAGRAPH. RIGHT: align to right

WD_ALIGN_PARAGRAPH. JUSTIFY: align both ends

Line spacing, segment spacing the line_spacing attribute is used to set the line spacing, space_before represents the segment leading distance, and space_after represents the segment trailing distance.

Italic, underlined, bold settin

Font.italic = True # set italic font.underline = True # set underline font.bold = True # set bold

The first line indent paragraph_format_line_indent can set the indentation value.

In addition to the above, other settings can also be set through document.styles.add_style ('textstyle', WD_STYLE_TYPE. PARAGRAPH), use the add_style () method to create a new style object, and then you can set the style through the properties provided, set the font to font.size, and set the font color to font.color.

Then when you add a paragraph, you can apply this attribute.

From docx.shared import RGBColorfrom docx.enum.style import WD_STYLE_TYPEstyle = document.styles.add_style ('textstyle', WD_STYLE_TYPE.PARAGRAPH) # Font size style.font.size = Pt (16) # Font color style.font.color.rgb = RGBColor (66,100,0) p1 = document.add_paragraph (' Divine Eraser', style=style) header and footer

The header and footer can be set directly. The reference code is as follows

Header = document.sections [0] .headerheader.add _ paragraph ('eraser header')

Footer settin

Footer = document.sections [0] .what are the main application areas of footerpython 1. Cloud computing, typical application OpenStack. 2. WEB front-end development, many large websites are developed by Python. 3. Artificial intelligence applications, which are based on big data's analysis and deep learning, have essentially been unable to leave python. 4. System operation and maintenance project, the standard configuration of automatic operation and maintenance is python+Django/flask. 5. Financial management analysis, quantitative transaction, financial analysis. 6. Big data's analysis.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report