excel中有圖片是很常見的,但是通過python讀取excel中的圖片沒有很好的解決辦法。
網(wǎng)上找了一種很聰明的方法,原理是這樣的:
1、將待讀取的excel文件后綴名改成zip,變成壓縮文件。
2、再解壓這個文件。
3、在解壓后的文件夾中,就有excel中的圖片。
4、這樣讀excel中的圖片,就變成了讀文件夾中的圖片了,和普通文件一樣,可以做各種處理。
解壓后的壓縮包如下:
python腳本如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
''' File Name: readexcelimg Author: tim Date: 2018/7/26 19:52 Description: 讀取excel中的圖片,打印圖片路徑 先將excel轉(zhuǎn)換成zip包,解壓zip包,包下面有文件夾存放了圖片,讀取這個圖片 ''' import os import zipfile # 判斷是否是文件和判斷文件是否存在 def isfile_exist(file_path): if not os.path.isfile(file_path): print ( "It's not a file or no such file exist ! %s" % file_path) return False else : return True # 修改指定目錄下的文件類型名,將excel后綴名修改為.zip def change_file_name(file_path, new_type = '.zip' ): if not isfile_exist(file_path): return '' extend = os.path.splitext(file_path)[ 1 ] # 獲取文件拓展名 if extend ! = '.xlsx' and extend ! = '.xls' : print ( "It's not a excel file! %s" % file_path) return False file_name = os.path.basename(file_path) # 獲取文件名 new_name = str (file_name.split( '.' )[ 0 ]) + new_type # 新的文件名,命名為:xxx.zip dir_path = os.path.dirname(file_path) # 獲取文件所在目錄 new_path = os.path.join(dir_path, new_name) # 新的文件路徑 if os.path.exists(new_path): os.remove(new_path) os.rename(file_path, new_path) # 保存新文件,舊文件會替換掉 return new_path # 返回新的文件路徑,壓縮包 # 解壓文件 def unzip_file(zipfile_path): if not isfile_exist(zipfile_path): return False if os.path.splitext(zipfile_path)[ 1 ] ! = '.zip' : print ( "It's not a zip file! %s" % zipfile_path) return False file_zip = zipfile.ZipFile(zipfile_path, 'r' ) file_name = os.path.basename(zipfile_path) # 獲取文件名 zipdir = os.path.join(os.path.dirname(zipfile_path), str (file_name.split( '.' )[ 0 ])) # 獲取文件所在目錄 for files in file_zip.namelist(): file_zip.extract(files, os.path.join(zipfile_path, zipdir)) # 解壓到指定文件目錄 file_zip.close() return True # 讀取解壓后的文件夾,打印圖片路徑 def read_img(zipfile_path): if not isfile_exist(zipfile_path): return False dir_path = os.path.dirname(zipfile_path) # 獲取文件所在目錄 file_name = os.path.basename(zipfile_path) # 獲取文件名 pic_dir = 'xl' + os.sep + 'media' # excel變成壓縮包后,再解壓,圖片在media目錄 pic_path = os.path.join(dir_path, str (file_name.split( '.' )[ 0 ]), pic_dir) file_list = os.listdir(pic_path) for file in file_list: filepath = os.path.join(pic_path, file ) print (filepath) # 組合各個函數(shù) def compenent(excel_file_path): zip_file_path = change_file_name(excel_file_path) if zip_file_path ! = '': if unzip_file(zip_file_path): read_img(zip_file_path) # main if __name__ = = '__main__' : compenent( '/Users/Desktop/test/people.xlsx' ) |
總結(jié)
以上所述是小編給大家介紹的Python讀取excel中的圖片完美解決方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/yangtze-yufei/p/9374454.html