十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章將為大家詳細講解有關python讀取excel表數(shù)據(jù)的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
python讀取excel表數(shù)據(jù)的方法:首先安裝Excel讀取數(shù)據(jù)的庫xlrd;然后獲取Excel文件的位置并且讀取進來;接著讀取指定的行和列的內(nèi)容,并將內(nèi)容存儲在列表中;最后運行程序即可。
python讀取excel表數(shù)據(jù)的方法:
1、安裝Excel讀取數(shù)據(jù)的庫-----xlrd
直接pip install xlrd安裝xlrd庫
#引入Excel庫的xlrd import xlrd
2、獲取Excel文件的位置并且讀取進來
#導入需要讀取Excel表格的路徑 data = xlrd.open_workbook(r'C:\Users\NHT\Desktop\Data\\test1.xlsx') table = data.sheets()[0]
3、讀取指定的行和列的內(nèi)容,并將內(nèi)容存儲在列表中(將第三列的時間格式轉換)
#創(chuàng)建一個空列表,存儲Excel的數(shù)據(jù) tables = [] #將excel表格內(nèi)容導入到tables列表中 def import_excel(excel): for rown in range(excel.nrows): array = {'road_name':'','bus_plate':'','timeline':'','road_type':'','site':''} array['road_name'] = table.cell_value(rown,0) array['bus_plate'] = table.cell_value(rown,1) #將Excel表格中的時間格式轉化 if table.cell(rown,2).ctype == 3: date = xldate_as_tuple(table.cell(rown,2).value,0) array['timeline'] = datetime.datetime(*date) array['road_type'] = table.cell_value(rown,3) array['site'] = table.cell_value(rown,4) tables.append(array)
4、運行程序
if __name__ == '__main__': #將excel表格的內(nèi)容導入到列表中 import_excel(table) #驗證Excel文件存儲到列表中的數(shù)據(jù) for i in tables: print(i)
5、最終的運行效果如下:
6、完整的程序代碼:
import xlrd from xlrd import xldate_as_tuple import datetime #導入需要讀取的第一個Excel表格的路徑 data1 = xlrd.open_workbook(r'C:\Users\NHT\Desktop\Data\\test.xlsx') table = data1.sheets()[0] #創(chuàng)建一個空列表,存儲Excel的數(shù)據(jù) tables = [] #將excel表格內(nèi)容導入到tables列表中 def import_excel(excel): for rown in range(excel.nrows): array = {'road_name':'','bus_plate':'','timeline':'','road_type':'','site':''} array['road_name'] = table.cell_value(rown,0) array['bus_plate'] = table.cell_value(rown,1) if table.cell(rown,2).ctype == 3: date = xldate_as_tuple(table.cell(rown,2).value,0) array['timeline'] = datetime.datetime(*date) array['road_type'] = table.cell_value(rown,3) array['site'] = table.cell_value(rown,4) tables.append(array) if __name__ == '__main__': #將excel表格的內(nèi)容導入到列表中 import_excel(table) for i in tables: print(i)
關于python讀取excel表數(shù)據(jù)的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。