import os
import docx
from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
from docx.oxml.ns import nsmap
import pandas as pd
import re
from lxml import etree
from docx.oxml.ns import qn
#判断表格是否有边框
def has_table_borders(table:Table):
#获取表格的tblPr
tblPr = table._element.find('w:tblPr', namespaces=nsmap)
tblBorders = tblPr.find('w:tblBorders', namespaces=nsmap)
#获取所有boarder的val
border_val_list=[border.get(qn('w:val')) for border in tblBorders]
#如果所有boarder的val中不全为"none"或不全为"nil",则返回True
if border_val_list.count('none')+border_val_list.count('nil')!=len(border_val_list):
return True #表格有边框
return False #表格无边框
#判断表格的每个单元格是否有框线
def has_cell_borders(table:Table):
#遍历表格的每个单元格
for row in table.rows:
for cell in row.cells:
#获取单元格的tcPr
tcPr = cell._tc.find('w:tcPr', namespaces=nsmap)
#tcBorders记录了'start', 'top', 'end', 'bottom', 'insideH', 'insideV'的边框信息
tcBorders = tcPr.find('w:tcBorders', namespaces=nsmap)
#如果tcBorders为None,则说明该单元格没有边框
if tcBorders is None:
continue
#获取所有boarder的val
border_val_list=[border.get(qn('w:val')) for border in tcBorders]
#如果所有boarder的val中不全为"none"或不全为"nil",则返回True
if border_val_list.count('none')+border_val_list.count('nil')+border_val_list.count(None)!=len(border_val_list):
return True
return False
border有以下几种属性:color、shadow、space、sz、val。通过val属性可以判断边框是实线、虚线还是无边框。关于这几种属性的详细信息可以参考这篇博客