Python自動批量Word數(shù)據(jù)到Excel
## 問題背景
我有很多個Word文件:

里面的每個word文件中,都有數(shù)據(jù)表格

怎樣把批量的word文件的表格數(shù)據(jù)提取出來,放到excel中呢

## 導(dǎo)入代碼包
用到了python-docs這個庫,需要自己安裝
# pip install python-docxfrom docx import Documentimport pandas as pdimport os
## 編寫解析函數(shù)
注意,當(dāng)做一個普通的table解析即可,用cell(row, col)讀取確定單元格的內(nèi)容文本。
def parse_docfile(doc_file):doc = Document(doc_file)table = doc.tables[0]return dict(= table.cell(0, 1).text, 性別 = table.cell(0, 3).text,= table.cell(0, 5).text, 出生年月 = table.cell(0, 7).text,= table.cell(1, 1).text, 學(xué)歷 = table.cell(1, 3).text,= table.cell(1, 5).text, 政治面貌 = table.cell(1, 7).text,= table.cell(2, 1).text, 專業(yè) = table.cell(2, 4).text,= table.cell(2, 7).text,= table.cell(3, 1).text, 報考類別 = table.cell(3, 7).text,= table.cell(4, 1).text.strip(),= table.cell(5, 1).text.strip(),= table.cell(6, 1).text.strip(),= table.cell(7, 1).text.strip(),)
## 單個word的測試
parse_docfile("優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(劉備).docx")輸出結(jié)果為:
{'姓名': '劉備','性別': '男','民族': '漢','出生年月': '1956.11','參加工作時間': '1975.7','學(xué)歷': '本科','籍貫': '成都','政治面貌': '蜀漢','畢業(yè)院校': '成都大學(xué)','專業(yè)': '體育','職務(wù)': '大將軍','工作單位': '成都第一中學(xué)','報考類別': '語文','工作簡歷': '從簡','工作業(yè)績': '優(yōu)秀','單位推薦意見': '同意','領(lǐng)導(dǎo)意見': '同意'}
## 結(jié)合os模塊,做批量解析
初始化結(jié)果數(shù)據(jù)結(jié)構(gòu)
# 列名columns = None# 數(shù)據(jù)內(nèi)容datas = []
實(shí)現(xiàn)for循環(huán)解析
for file in os.listdir("優(yōu)秀教師選拔考試報名表"):if file.endswith(".docx"):file_path = f"優(yōu)秀教師選拔考試報名表/{file}"print("解析文件", file_path)data = parse_docfile(file_path)if not columns:columns = list(data.keys())datas.append([data[column] for column in columns])
程序輸出結(jié)果為:
解析文件 優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(張飛).docx解析文件 優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(周瑜).docx解析文件 優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(曹操).docx解析文件 優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(小喬).docx解析文件 優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(曹植).docx解析文件 優(yōu)秀教師選拔考試報名表/優(yōu)秀教師選拔考試報名表(劉備).docx
## 使用pandas輸出到excel文件
df = pd.DataFrame(datas, columns = columns)df.to_excel("優(yōu)秀教師選拔考試報名表.xlsx", index=False)
查看結(jié)果excel文件:

## 本代碼的視頻講解
謝謝,如果對你幫助,點(diǎn)個贊呀!
評論
圖片
表情
