python提取word表格的操作相对简单,但是有时候我们会遇到提取的是嵌套表格的情况,这需要一点技巧,本文就分享一个简单的案例
需要提取的表格中嵌套了子表格
大概就是上面的样子,处理结果是嵌套的子表格,并且右边的具体内容又是一个嵌套的表格
处理代码如下
from docx import Document
import xlsxwriter
#设置文件的目录
path="投诉件.docx"
# 存储我们刚刚读出来的数据
dict = {}
# 解析传入的文件,将信息填入dict
def getdict(path):
wordfile = Document(path)
# 遍历每一行
for i in range(len(wordfile.tables[1].rows)):
for j in range(len(wordfile.tables[1].rows[i].cells)):
#print(str(i) + " " + str(j) + " " + wordfile.tables[1].rows[i].cells[j].text)
if(i==5 and j==1):
dict["来电内容"] = wordfile.tables[1].rows[i].cells[j].text
elif(i==8 and j==3):
dict["限办日期"] = wordfile.tables[1].rows[i].cells[j].text
# 检查嵌套表
if(len(wordfile.tables[1].rows[i].cells[j].tables) != 0):
table1 = wordfile.tables[1].rows[i].cells[j].tables[0]
checksubtable(table1)
# 检查嵌套表
def checksubtable(table1):
# 如果已经拿到了办理结果,就返回
if(len(dict)==3):
return
for k in range(len(table1.rows)):
for h in range(len(table1.rows[k].cells)):
if(len(table1.rows[k].cells[h].tables)!=0):
table2 = table1.rows[k].cells[h].tables[0]
dict["处理结果"] = table2.rows[0].cells[0].text
# 将dict存入csv文件
def write_excel():
# 生成excel文件名
expath = path.split(".")[0] + ".xlsx"
workbook = xlsxwriter.Workbook(expath)
worksheet = workbook.add_worksheet()
bold_format = workbook.add_format({'bold': True})
# 设置列宽
worksheet.set_column("A:A", 20)
worksheet.set_column("B:B", 50)
worksheet.set_column("C:C", 50)
# 首先写标题
worksheet.write("A1", "限办日期", bold_format)
worksheet.write("B1", "来电内容", bold_format)
worksheet.write("C1", "处理结果", bold_format)
# 填写内容
worksheet.write_string(1, 0, dict["限办日期"])
worksheet.write_string(1, 1, dict["来电内容"])
worksheet.write_string(1, 2, dict["处理结果"])
# 关闭文件流
workbook.close()
if __name__ == "__main__":
getdict(path)
write_excel()
运行上述代码就能在py文件所在的文件夹生成对应名称的excel文件。
大体思路就是这样,对于特定的需求,只需要按照上述的思路修改代码即可。