头图
For the original address, video demonstration effect and code acquisition, please click below

hyperlink is here! ! ! !

Video presentation effect

Preface

在这里插入图片描述

A young lady asked me in the background. Recently, there was an event in the company. There was a form with hundreds of people and an invitation template document. Recently, I accidentally swiped it. Pictured above!

在这里插入图片描述
Although you may not understand what you are talking about, you do not copy and paste the content to me, if I guessed it correctly. It should look like this:

Replace right *** content with left unit + name or name

untitled

, so it’s qualitative for the time being: Use 160c9e7d27446d Python to generate word version invitations

Daily water:

  • Module

    • openpyxl in load_workbook method.
    • docx (sell a pass here, if you want to see the complete one, please click on the hyperlink)
  • download.

    • pip install openpyxl

Get information about invitees

We first import the openpyxl module in the load_workbook module.

from openpyxl import load_workbook

We use load_workbook(path) read the file and store it in the variable wb .

wb=load_workbook('data/name_list.xlsx')
ws=wb['name']

Next we need to select the "Sheet" we need, which is the sheet named "name"

ws=wb['name']

Then define an empty list names to store the unit and name information of the invitees. Then we traverse the worksheet, extract all the information and save it in the list names , because the first line of the worksheet is the title, so we start from the second line, and the largest line +1 ends at range(2,ws.max_row+1) .

names=[]
for row in range(2,ws.max_row+1):
    company=ws["A"+str(row)].value
    name=ws["B"+str(row)].value
    names.append(f" {company} {name} ")

After the above steps are completed, we can start to generate invitation letters in batches. First import the library that handles word

import docx

docx.Document('data/invitation letter.docx') is a fixed wording. Fill in the path and file name of the invitation template in parentheses. doc can be understood as this word file named "invitation letter". Then traverse the names list, and write the information in the third run of the second paragraph of the word file one by one, that is, doc.paragraphs[1].runs[2].text=name , and finally, save it save

doc=docx.Document('data/邀请函.docx')
for run in doc.paragraphs[1].runs:
    for name in names:
        run.text = run.text.replace('****', name)
        doc.save(f'data/邀请函_{name}.docx')

effect


CoXie带你学编程
195 声望13 粉丝