python讀取Excel表格文件的方法
python讀取Excel表格文件,例如獲取這個(gè)文件的數(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)容存儲(chǔ)在列表中(將第三列的時(shí)間格式轉(zhuǎn)換)
#創(chuàng)建一個(gè)空列表,存儲(chǔ)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表格中的時(shí)間格式轉(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、運(yùn)行程序
if __name__ == '__main__':
#將excel表格的內(nèi)容導(dǎo)入到列表中
import_excel(table)
#驗(yàn)證Excel文件存儲(chǔ)到列表中的數(shù)據(jù)
for i in tables:
print(i)
5、最終的運(yùn)行效果如下:

6、完整的程序代碼:
import xlrd
from xlrd import xldate_as_tuple
import datetime
#導(dǎo)入需要讀取的第一個(gè)Excel表格的路徑
data1 = xlrd.open_workbook(r'C:\Users\NHT\Desktop\Data\\test.xlsx')
table = data1.sheets()[0]
#創(chuàng)建一個(gè)空列表,存儲(chǔ)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表格文件的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
Python?Math數(shù)學(xué)函數(shù)常數(shù)冪和對(duì)數(shù)基礎(chǔ)應(yīng)用實(shí)例
Python中的math模塊是數(shù)學(xué)運(yùn)算的重要工具,提供了豐富的數(shù)學(xué)函數(shù)和常數(shù),本文將深入探討math模塊的功能和用法,使您能夠更好地利用Python進(jìn)行數(shù)學(xué)運(yùn)算2023-12-12
python 調(diào)用API接口 獲取和解析 Json數(shù)據(jù)
這篇文章主要介紹了python 如何調(diào)用API接口 獲取和解析 Json數(shù)據(jù),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-09-09
Python TCP接收數(shù)據(jù)不全的問題解決
本文主要介紹了Python TCP接收數(shù)據(jù)不全的問題解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
Python Opencv實(shí)現(xiàn)圖像輪廓識(shí)別功能
這篇文章主要為大家詳細(xì)介紹了Python Opencv實(shí)現(xiàn)圖像輪廓識(shí)別功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04

