1.讀取Excel表格
panda方式 ,普通的excel可行,對於有些數據復雜的,可能提取不了
import pandas
excel=pandas.read_excel('現代征信學.xlsx',index_col='列名',header=None) #header默認為0,指讀取第幾行,0代表第一行
print(excel)
xlrd方式
#讀取excel表格
def readExcelTable(file_path,sheetName):
table = xlrd.open_workbook(file_path)
#sheet=table.sheet_by_index(0)# 用下標的方式選擇要讀取文件中的工作表,也可用工作表的名稱 sheet=work.sheet_by_name('Sheet1')
sheet = table.sheet_by_name(sheetName)
print(sheet)
print(range(sheet.nrows))
# 遍歷excel,打印所有數據
for i in range(sheet.nrows):
if i>0:
item=sheet.row_values(i)
numId='0'
if item[0]!=None and item[0]!='':
numId=str(int(item[0]))
jItem = {'Id':numId,'Pic': str(item[2])+'.png', 'Code':str(item[2]), 'TypeName': str(item[3]), 'Oe': str(item[4]), 'Brand': str(item[5]),'Car':'','Size':str(item[7]),'Package':str(item[8]),'Memo':str(item[9])};
print(jItem)
MSSQL().insertProduct(jItem)
2.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)