将doc中的表格转为df的python程序

首先安装必要包

pip install python-docx pandas

然后运行代码:

import pandas as pd
from docx import Document

def docx_table_to_df(docx_path, table_index):
    """
    将Word文档中的表格转换为DataFrame。

    :param docx_path: Word文档的路径。
    :param table_index: 表格在文档中的索引(从0开始)。
    :return: 转换后的DataFrame。
    """
    # 加载Word文档
    doc = Document(docx_path)
    
    # 获取指定索引的表格
    table = doc.tables[table_index]
    
    # 提取表格数据
    data = [[cell.text for cell in row.cells] for row in table.rows]
    
    # 将数据转换为DataFrame
    df = pd.DataFrame(data[1:], columns=data[0])  # 假设第一行是列名
    return df

# 使用示例
docx_file = 'path_to_your_doc.docx'  # 替换为你的Word文档路径
table_idx = 0  # 替换为你要转换的表格的索引

# 转换表格
df = docx_table_to_df(docx_file, table_idx)

# 打印DataFrame
print(df)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Icy Hunter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>