使用 docx 库读取 Word 中表格数据

需求如下图:
使用 docx 库读取 Word 中表格数据

从下图 Word 表格中,读取填入的数据,并进行判断选项,最终将数据填入客户系统。

代码处理如下:

方法 1(不推荐)

  import docx
  from docx import Document #导入库

  path = r"\\Mac\Home\Desktop\\asd.docx" #文件路径
  document = Document(path) #读入文件
  tables = document.tables #获取文件中的表格集
  table = tables[0]#获取文件中的第一个表格
  list = []
  print(table.cell)
  for i in range(0,len(table.rows)):#从表格第1行开始循环读取表格数据
	  for j in range(0,7):
		  result = table.cell(i,j).text
		  #cell(i,0)表示第(i+1)行第1列数据,以此类推
		  # print(result)
		  a = result.split("\n")
		  if a not in list:
			  list.append(a)
  print(list)

最终读取到如下:
使用 docx 库读取 Word 中表格数据

为了方便显示,已将每个小列表进行换行处理。最终便可在得到的列表中取到想要的数据了。Word 表格中若为空行,读出来的数据则为 ['']

方法 2(推荐)

def read_word_table2(file_path):
	doc=Document(file_path)
	value=[]
	table_index=0
	for tb in doc.tables:
		table_index+=1
		row_index=0
		for row in tb.rows:
			row_index+=1
			for cell in row.cells:
				text=""
				for p in cell.paragraphs:     #如果cell中有多段,即有回车符
					text+=p.text
					print(text)
					value.append([text])
	print(value)