把word中表格转成excle文件

把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}")
相关推荐
IT_Octopus43 分钟前
JSON 日志里的 `{“$ref“:“$.xxx“}`:从 fastjson 兼容包到原生 fastjson2 的迁移实录
开发语言·python·json
geovindu44 分钟前
python:HandWriting Recognition using paddlepaddle
开发语言·后端·python·paddlepaddle
wuyk5551 小时前
Python 零基础入门第九章:用户输入与 While 循环
开发语言·python
兮动人1 小时前
Python变量与常量
开发语言·python·机器学习·python变量与常量
风筝在晴天搁浅1 小时前
解题代码清爽版
java·开发语言
Java后端的Ai之路2 小时前
21、Python - 命令模式
开发语言·人工智能·python·命令模式·外观模式
astronautyi2 小时前
Go 运行时内存分配与 GC 位图深度剖析
开发语言·后端·golang
techdashen2 小时前
Go 中如何处理错误
开发语言·后端·golang
孙克旭_2 小时前
JVM 入门详解:JVM、JRE、JDK 区别,JVM 基础结构梳理
java·开发语言·jvm
随遇而安zx2 小时前
【地基篇】---JVM 内存结构知识点(Java 8 运行时数据区深度解析)
java·开发语言·jvm