python讀取Excel表格文件,例如獲取這個文件的數(shù)據(jù)
python讀取Excel表格文件,需要如下步驟:
1、安裝Excel讀取數(shù)據(jù)的庫-----xlrd
直接pip install xlrd安裝xlrd庫
#引入Excel庫的xlrd import xlrd
2、獲取Excel文件的位置并且讀取進(jìn)來
#導(dǎo)入需要讀取Excel表格的路徑 data = xlrd.open_workbook(r'C:\Users\NHT\Desktop\Data\\test1.xlsx') table = data.sheets()[0]
3、讀取指定的行和列的內(nèi)容,并將內(nèi)容存儲在列表中(將第三列的時間格式轉(zhuǎn)換)
#創(chuàng)建一個空列表,存儲Excel的數(shù)據(jù) tables = [] #將excel表格內(nèi)容導(dǎo)入到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表格中的時間格式轉(zhuǎn)化 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)容導(dǎo)入到列表中 import_excel(table) #驗證Excel文件存儲到列表中的數(shù)據(jù) for i in tables: print(i)
5、最終的運行效果如下:
6、完整的程序代碼:
import xlrd from xlrd import xldate_as_tuple import datetime #導(dǎo)入需要讀取的第一個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)容導(dǎo)入到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)容導(dǎo)入到列表中 import_excel(table) for i in tables: print(i)
總結(jié)
以上所述是小編給大家介紹的python讀取Excel表格文件的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
