1. 程式人生 > 實用技巧 >給定列表,按照列表內容獲取excel指定列名下的內容(利用openpyxl實現,目前獲取第一行內容)

給定列表,按照列表內容獲取excel指定列名下的內容(利用openpyxl實現,目前獲取第一行內容)

excel檔案內容如下:

想要實現的功能:指定想要獲取的列名,返回列名和內容的字典

栗子:輸入:columnname=["姓名","年齡","班級","身高"]

預期返回:{'姓名': '小李', '年齡': 15, '班級': '3年2班', '身高': 162}

輸入:columnname=["姓名","班級","身高"]

預期返回:{'姓名': '小李','班級': '3年2班', '身高': 162}

 1 '''
 2 功能說明:file是檔案路徑,namelist是想要獲取內容的excel列名
 3 '''
 4 import openpyxl
5 def getdata(file,namelist): 6 workbook=openpyxl.load_workbook(file) 7 sheet=workbook['Sheet1'] 8 columnnamecell=sheet['1'] #獲取第一行的所有cell 9 columnname=[y.value for y in columnnamecell ] #namelist中欄位在excel中的行數列表 10 mapping={} 11 for x in namelist: 12 index_num=columnname.index(x)+1 #
excel索引和陣列索引差1 13 mapping[x]=sheet.cell(2,index_num).value 14 return mapping 15 16 if __name__=="__main__": 17 column_name=["姓名","年齡","班級","身高"] 18 file="test.xlsx" 19 dic=getdata(file,column_name) 20 print(dic)

輸出:

D:\pythonprogrem\get_excel_data\venv\Scripts\python.exe D:/pythonprogrem/get_excel_data/getdata.py
{
'姓名': '小李', '年齡': 15, '班級': '3年2班', '身高': 162}