将docx中的表格读入pandas
from docx import Document
import pandas as pd
import polars as pl
def tables_to_pd(word_file):
doc = Document(word_file)
all_data = [] # 存储所有表格的数据行
headers = None # 存储表头
for i, table in enumerate(doc.tables):
for j, row in enumerate(table.rows):
row_data = [cell.text for cell in row.cells]
if j == 0: # 第一行作为表头
if headers is None:
headers = row_data # 只保存第一个表格的表头
else: # 数据行
all_data.append(row_data)
# 创建一个DataFrame
if headers and all_data:
df = pd.DataFrame(all_data, columns=headers)
return df
df1=tables_to_pd(
"/mnt/c/Users/Administrator/Downloads/调查对象信息和基本信息表-通渭县.docx"
)
评论
发表评论