Python将Word转换为Excel

现有大量的Word文档,每个文档中有大量的表格,需要将其转换为Excel。

Python处理源码

python 复制代码
# 需要安装pip install xlsxwriter
import pandas as pd
from docx import Document
from pathlib import Path
from datetime import datetime

def process_docx(filepath):
    # 处理Word文档的主函数
    doc = Document(filepath)
    # 示例处理逻辑:提取所有段落文本
    content = [p.text for p in doc.paragraphs if p.text.strip()]
    print(f"成功处理文档: {filepath}")
    data = []
    monitor_time = ""
    # 提取监测时间
    for paragraph in doc.paragraphs:
        # print(paragraph.text)
        if "第12次:" in paragraph.text:
            monitor_time = parse_monitor_time(paragraph.text)
            print(f"提取监测时间: {monitor_time}")
            break

    # 处理所有表格
    index = 0
    for table in doc.tables:
        # 检查是否为数据表格(包含房屋编号列)
        if len(table.columns) >= 7 and "成果表" in table.cell(0,0).text:
            # print(table.cell(0,0).text)
            for row in table.rows[2:]:  # 跳过标题行
                first_cell_text = row.cells[0].text.strip()  # 获取第一个单元格的文本并去除首尾空格
                if "备注" in first_cell_text:  # 如果第一个单元格包含"备注"
                    continue  # 跳过该行
                cells = [cell.text.replace("\n", "").replace("\r", "").strip() for cell in row.cells]
                if len(cells) >= 7:  # 确保数据完整
                    # 构建输出记录
                    record = {
                        '点号': f"{cells[0].replace(" ", "")}-{cells[1]}",
                        '初始值': cells[2],
                        '检测值': cells[3],
                        '累计值': cells[4],
                        '监测时间': monitor_time,
                        '上次监测时间': "2025/6/17 03:00"  # 根据备注补充
                    }
                    # print(record)
                    data.append(record)
    return data


def generate_excel(data, output_path):
    # 生成标准格式Excel
    df = pd.DataFrame(data) 

    # 补充固定字段
    df['备注'] = '无'

    # 字段顺序调整
    columns_order = [ '点号', '初始值', '检测值', '累计值', '监测时间', '上次监测时间', '备注' ]
    df = df.reindex(columns=columns_order)

    # 填充空值
    df['上次监测时间'] = '2025-06-01'

    # 保存Excel
    # df.to_excel(output_path, index=False)
    with pd.ExcelWriter(output_path, engine='xlsxwriter') as writer:
        df.to_excel(writer, index=False, sheet_name='Sheet1')  # 导出数据
        worksheet = writer.sheets['Sheet1']
        # 手动设置列宽(单位:字符宽度)
        worksheet.set_column('A:A', 38)  # 设置A列为15字符宽度
        worksheet.set_column('B:B', 12)  # 设置B列为10字符宽度
    print(f"Excel文件已生成: {output_path}")

print(f"Excel开始生成")
filepath=r"C:\Users\admin\Desktop\test.docx"
output_path=r"C:\Users\admin\Desktop\test.xlsx"
data = process_docx(filepath)
generate_excel(data, output_path)
print(f"Excel生成结束")

输入Word文档

word文档格式如下所示

输出Excel文档

相关推荐
jufeng130739 分钟前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 8 篇】
python·ai agent·配置系统
circuitsosk1 小时前
跨境电商智能化实战:AI如何赋能客服自动回复、广告智能投放与供应链预测
大数据·人工智能·python·langchain·智能客服
2601_956319882 小时前
2026年零基础学量化:从看懂示例到写清条件和动作
人工智能·python
过期的秋刀鱼!2 小时前
LangChain-D1-模型的工作流程
人工智能·python·langchain
萤火工厂目视化设计2 小时前
智能制造与企业文化目视化浪潮下:中小工厂的机遇与挑战
python·制造
wujian83113 小时前
怎么用千问生成word文档:从「格式崩」到「一键过」,AI导出鸭打通最后半厘米
人工智能·ai·c#·word·豆包·deepseek·ai导出鸭
DeepVisionary3 小时前
从GPT-5.6 Sol的Ultrafast模式看推理速度竞赛:750 token/秒背后,Cerebras的晶圆级生意
python·自动化
leisoo80974 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法
小柯南敲键盘4 小时前
跨马翻译:跨境电商批量图片翻译与视频字幕一站式工具
人工智能·python·音视频
卷无止境5 小时前
FastAPI Guard 全解析,从概念到工程落地的实战指南
后端·python