首先安装必要包
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)
1158

被折叠的 条评论
为什么被折叠?



