python读取excel图片

原理都是通过rar模式获取excel的资源文件,如:

将“奥圣2021-04-10((1).xls” 重命名为“奥圣2021-04-10((1).rar”

图片目录都在\media下

图片和excel行的对应关系是 drawing1.xml,总的来说 如果这个excel文件的数据不是 那么规范的话,处理还是有点麻烦的

用IE浏览器打开drawing1.xml

那么接下来的问题就是 读取这个xml,并找到对应关系,进行相应的重命名或存储了

#excel变成压缩包后,图片是在media目录下面,但文件名是顺序递增的序号
#其中 <a:blip r:embed="rId52"/> 节点对应图片序号
#<xdr:cNvPr descr="机滤AO62121" name="Picture 251" id="3784784"/> 对应图片描述
#<xdr:row>141</xdr:row> 对应excel行号
def zipXmlRead(zipfile_path,image_path):
    dir_path = os.path.dirname(zipfile_path)  # 获取文件所在目录
    file_name = os.path.basename(zipfile_path)  # 获取文件名
    unzip_dir = os.path.join(dir_path, str(file_name.split('.')[0]))
    xml_name = 'xl' + os.sep + 'drawing1'+os.sep+'drawing1.xml'  # excel变成压缩包后,再解压,drawing1对应就是sheet1的说明
    xml_name = 'xl/drawings/drawing1.xml'
    ns = {'i': 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing','a':'http://schemas.openxmlformats.org/drawingml/2006/main','r':'http://schemas.openxmlformats.org/drawingml/2006/relationships'}
    fz = zipfile.ZipFile(zipfile_path, 'r')
    xml_string = fz.read(xml_name).decode()
    xml = ET.fromstring(xml_string)
    nodes = xml.findall('.//i:from/i:row', ns) #test:找行号
    for node in nodes:
        #print(node) 测试
        continue
    nodes=xml.findall(".//i:pic/i:blipFill/a:blip",ns) #test:找图片节点
    for node in nodes:
        #print(node.attrib) 测试
        continue
    nodes=xml.findall('.//i:twoCellAnchor',ns) #找到父节点,再遍历子节点
    for node in nodes:
        row=node.find('.//i:from/i:row', ns)#获取行号
        rowNum=row.text
        descr=''
        descrNode=node.find('.//i:nvPicPr/i:cNvPr',ns) #获取描述
        if 'descr' in descrNode.attrib:
            descr=descrNode.attrib['descr']
        rid=node.find('.//i:blipFill/a:blip',ns).attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed'] #获取图片资源序号
        print('行号:'+str(rowNum)+' 描述:'+descr+' 图片顺序:'+rid)
        imgId=str(rid).replace('rId','') #
        proCode=MSSQL().getCodeById(int(rowNum))
        picName=rowNum+'.png'
        newPicName=str(proCode)
        try:
            os.rename(image_path+'\\image'+picName,image_path+'\\'+newPicName+'.png')
        except IOError as e:
           print(e)

  

posted on 2023-04-04 08:38  帅胡  阅读(248)  评论(0编辑  收藏  举报

导航