search
HomeBackend DevelopmentPython TutorialPython操作Word批量生成文章的方法

下面通过COM让Python与Word建立连接实现Python操作Word批量生成文章,具体介绍请看下文:

需要做一些会议记录。总共有多少呢?五个地点x7个月份x每月4篇=140篇。虽然不很重要,但是140篇记录完全雷同也不好。大体看了一下,此类的记录大致分为四段。于是决定每段提供四种选项,每段从四选项里随机选一项,拼凑成四段文字,存成一个文件。而且要打印出来,所以准备生成一个140页的Word文档,每页一篇。

需要用到win32com模块(下载链接: http://sourceforge.net/projects/pywin32/files/ ),

通过COM让Python与Word建立连接。代码如下:

# -*- coding: cp936 -*-
#导入随机数模块
import random
#导入win32com模块,用来操作Word
import win32com 
from win32com.client import Dispatch, constants
#创建新的WORD文档
w = win32com.client.Dispatch('Word.Application')
w.Visible = 0#0表示在后台操作。设为1则在前端能看到Word界面。
w.DisplayAlerts = 0#不显示警告
doc = w.Documents.Add()
#准备对文档头部进行操作
myRange = doc.Range(0,0)#从第0行第0个字开始:
myRange.Style.Font.Name = "宋体"#设置字体
myRange.Style.Font.Size = "16"#设置为三号
#========以下为文章的内容部分=======
#文章标题(用\n来控制文字的换行操作)
title='XXXXX会\n会议时间: '
#会议时间
timelist=['1月9日','1月16日','1月23日','1月30日',
 '2月6日','2月13日','2月20日','2月27日',
 '3月6日','3月13日','3月20日','3月27日',
 '4月3日','4月10日','4月17日','4月24日',
 '5月8日','5月15日','5月22日','5月29日',
 '6月5日','6月12日','6月19日','6月26日',
 '7月3日','7月10日','7月17日','7月24日'
 ]
#会议地点
addrlist=['\n会议地点: 地点AXXX\n主持人: 张X\n',
 '\n会议地点: 地点BXXXX主持人: 吴X\n',
 '\n会议地点: 地点CXXXX\n主持人: 王X\n',
 '\n会议地点: 地点DXXXX\n主持人: 冉X\n',
 '\n会议地点: 地点EXXXX\n主持人: 李X\n',
 ]
#参加人员
member='参加人员: XXX,XXX,XXX,XXX,XXX,XXX,XXX。\n会议内容:\n '
#四段文字
list1=['第一段(A型)\n','第一段(B型)\n','第一段(C型)\n','第一段(D型)\n']
list2=['第二段(A型)\n','第二段(B型)\n','第二段(C型)\n','第二段(D型)\n']
list3=['第三段(A型)\n','第三段(B型)\n','第三段(C型)\n','第三段(D型)\n']
list4=['第四段(A型)\n','第四段(B型)\n','第四段(C型)\n','第四段(D型)\n']
#开始循环操作,往Word里面写文字
 #先开始遍历地点(A,B,C,D,E四个地区)
for addr in addrlist:
 #遍历28个日期
 for time in timelist:
 #随机生成四个数(范围0-3)
 aa=random.randint(0,3)
 bb=random.randint(0,3)
 cc=random.randint(0,3)
 dd=random.randint(0,3)
 #从文件开头依次插入标题、时间、地点、人物
 myRange.InsertAfter(title)
 myRange.InsertAfter(time)
 myRange.InsertAfter(addr)
 myRange.InsertAfter(str3)
 #在后面继续添加随机选取的四段文字
 myRange.InsertAfter(list1[aa])
 myRange.InsertAfter(list2[bb])
 myRange.InsertAfter(list3[cc])
 myRange.InsertAfter(list4[dd])
#循环完毕,保存为 D:\d.doc
doc.SaveAs(r'D:\d.doc')
#退出操作
doc.Close()
w.Quit()


最终结果如图:

================================================================

==============================================================

写在最后:

由于写的比较仓促,所以有些细节问题没能解决,花了20分钟手动调整了一下。觉得有些屈辱。问题如下:

1.正文是三号字体,所以在range处的字号设置了“16”。想让题目是二号字体、居中显示。

2.如何在第四段写完之后,自动插入一个分页符?这样每篇文章打印出来的都有独立的页,不至于出现“第2篇文章的标题紧跟在第1篇文章的屁股后面、打印在了同一张纸上”的情况。

以上就是本文全部介绍,希望对大家学习Python操作Word批量生成文章的方法有所帮助

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.