Python自动批量转换Doc为Docx并提取表格
利用Python脚本,实现自动批量将文件夹中的Doc文件转换成Docx格式,并提取其中的表格,最终生成新的Docx文件。虽然代码存在一些粗糙之处,但已经可以达到基本使用的要求,也可根据需要进一步优化和改进。具体实现方式及说明可参考以下代码:
import os
from docx import Document
def convert_and_extract(path):
"""
将指定路径下的所有Doc文件转换成Docx格式,并提取其中的表格
"""
for filename in os.listdir(path):
# 判断文件是否为Doc格式
if filename.endswith('.doc'):
# 构造文件路径
filepath = os.path.join(path, filename)
# 转换为Docx格式
docx_filename = filename.replace('.doc', '.docx')
docx_filepath = os.path.join(path, docx_filename)
os.system(f'start winword /mFileConvertor.ConvertToDocx "{filepath}" "{docx_filepath}"')
# 提取表格内容到新的Docx文件
doc = Document(docx_filepath)
table_text = '\n'.join([cell.text for table in doc.tables for row in table.rows for cell in row.cells])
new_docx_filepath = os.path.join(path, 'table_extracted_' + docx_filename)
new_doc = Document()
new_doc.add_paragraph(table_text)
new_doc.save(new_docx_filepath)
print('转换和提取表格完成')
if name == 'main':
# 要批量转换和提取表格的文件夹路径
folder_path = r'C:\Users\user\Desktop\test'
convert_and_extract(folder_path)