Py学习——批量操作Word文件
这几天为了帮助我姐批量修改Word的表格,让我想到了朋友圈常有的广告(路人:你咋这么快就做好了呀,主角:因为我用了Python呀,Python经典课程,免费上课。。。。。。)因此决定去用Python写一个简易的批量操作Word文件的代码。
用Py批量操作Word首先要安装一个库,安装命令如下:
pip install python-docx
官网地址如下:
https://python-docx.readthedocs.io/en/latest/
官方也给了一个Demo提供学习。
对于我这次的要求,是要能够批量修改不同word文件下的表格,需要实现的效果是: 能够自动往后写表格,除了日期不同,数据都相同

因为文件数目较多,因此首先需要的是对文件夹路径下的所有文件名进行存储,这里从网上Copy了一段代码,效果还蛮好使得
def folder_filelist(pathname): ''' 读取所有文件名,为了实现对文件夹的批处理 ''' filename_list = list() full_pathname = os.path.abspath(pathname) print(full_pathname) if os.path.isfile(full_pathname): if _is_legal_postfix(full_pathname): filename_list.append(full_pathname) else: raise TypeError('文件 {} 后缀名不合法!仅支持如下文件类型:{}。'.format(pathname, '、'.join(self._handle_postfix))) elif os.path.isdir(full_pathname): for relpath, _, files in os.walk(full_pathname): for name in files: filename = os.path.join(full_pathname, relpath, name) if _is_legal_postfix(filename): filename_list.append(os.path.join(filename)) return filename_list else: raise TypeError('文件 {} 不存在或不合法!'.format(pathname)) def _is_legal_postfix(filename): ''' 对文件种类进行识别 ''' _handle_postfix = ['doc', 'docx'] return filename.split('.')[-1].lower() in _handle_postfix and not os.path.basename(filename).startswith( '~')
这里主要是想要描述一个遇到得问题,在操作时发现,直接添加的字体他是固定的五号字体和Calibri字体,而我这个表格需要四号宋体,但网上的一些教程说不能对中文进行字体修改的操作,在我搜了很多资料,甚至翻墙之后,找到了解决办法:
for row in table.rows: for cell in row.cells: paragraphs = cell.paragraphs for paragraph in paragraphs: for run in paragraph.runs: font = run.font font.size= Pt(30)
亲测好使