返回
用Python魔法,一键批量解析Word中的表格内容
闲谈
2023-10-23 03:50:26
在职场中,我们经常会遇到需要处理各种文档的情况,其中Word文档中的表格内容也需要经常被提取到Excel中进行整理。以往,这一过程只能通过手动复制粘贴来完成,不仅耗费时间和精力,还容易出错。今天,我们来看看如何利用Python轻松实现这一操作,一键批量解析Word中的表格内容,写入Excel,解放双手,提高效率。
代码实现
import docx
import openpyxl
import os
# 获取指定目录下所有Word文档
def get_word_files(directory):
word_files = []
for file in os.listdir(directory):
if file.endswith(".docx"):
word_files.append(os.path.join(directory, file))
return word_files
# 从Word文档中提取表格内容
def extract_table_from_word(word_file):
doc = docx.Document(word_file)
tables = []
for table in doc.tables:
table_data = []
for row in table.rows:
row_data = []
for cell in row.cells:
row_data.append(cell.text)
table_data.append(row_data)
tables.append(table_data)
return tables
# 将表格内容写入Excel文件
def write_table_to_excel(excel_file, tables):
wb = openpyxl.Workbook()
for table in tables:
ws = wb.create_sheet()
for row_index, row in enumerate(table):
for col_index, cell in enumerate(row):
ws.cell(row=row_index + 1, column=col_index + 1).value = cell
wb.save(excel_file)
# 主函数
if __name__ == "__main__":
# 获取Word文档所在的目录
word_directory = input("请输入Word文档所在目录:")
# 获取Excel文件保存目录
excel_directory = input("请输入Excel文件保存目录:")
# 获取Word文档列表
word_files = get_word_files(word_directory)
# 逐个处理Word文档
for word_file in word_files:
# 提取表格内容
tables = extract_table_from_word(word_file)
# 将表格内容写入Excel文件
excel_file = os.path.join(excel_directory, word_file.split(".")[0] + ".xlsx")
write_table_to_excel(excel_file, tables)
# 提示用户操作完成
print("表格内容已批量解析并写入Excel文件,请前往Excel文件保存目录查看。")
注意事项
- 确保您已安装Python以及必要的库,例如docx、openpyxl。
- 将Word文档和Python脚本放在同一目录下。
- 运行脚本时,需要将Word文档所在的目录和Excel文件保存目录作为参数传递给脚本。
- 脚本将自动生成一个与Word文档同名的Excel文件,并将其保存在指定目录中。
- 脚本将逐个处理Word文档中的表格,并将其内容写入Excel文件中。
总结
通过本文,您将学会如何使用Python批量解析Word文档中的表格内容,并将其写入Excel文件中。这种自动化办公的技巧可以帮助您提高工作效率,节省时间和精力。