把word中表格转成excle文件
python
from docx import Document
from openpyxl import Workbook
from pathlib import Path
# 打开 Word 文档
document = Document('./weather_report.docx')
tables = document.tables
# 输出文件路径
output_file = Path('./weather_report.xlsx')
# 如果文件已存在,删除旧文件
if output_file.exists():
print(f"🚮 {output_file} 已存在,删除...")
output_file.unlink()
# 创建 Excel 工作簿
merged_wb = Workbook()
# 如果 Word 中没有表格,跳过保存
if not tables:
print("❌ Word 文档中未找到任何表格。")
else:
for i, t in enumerate(tables, start=1):
# 第一个表使用默认的 active sheet,其余的新增
if i == 1:
ws = merged_wb.active
ws.title = f"Table{i}"
else:
ws = merged_wb.create_sheet(title=f"Table{i}")
for row in t.rows:
row_data = [cell.text.strip() for cell in row.cells]
ws.append(row_data)
# 保存 Excel 文件
merged_wb.save(output_file)
print(f"✅ 所有表格已成功保存到 {output_file}")