python讀取excel表資料的方法:首先安裝Excel讀取資料的庫xlrd;然後擷取Excel檔案的位置并且讀取進來;接着讀取指定的行和列的内容,并将内容存儲在清單中;最後運作程式即可。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SZjFjYhBTMhFjMiBjZjJGN4E2NxEWYhFzMlRmZ2YmZh9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
python讀取excel表資料的方法:
1、安裝Excel讀取資料的庫-----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、讀取指定的行和列的内容,并将内容存儲在清單中(将第三列的時間格式轉換)#建立一個空清單,存儲Excel的資料
tables = []
#将excel表格内容導入到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表格的内容導入到清單中
import_excel(table)
#驗證Excel檔案存儲到清單中的資料
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]
#建立一個空清單,存儲Excel的資料
tables = []
#将excel表格内容導入到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表格的内容導入到清單中
import_excel(table)
for i in tables:
print(i)更多相關免費學習推薦:python視訊教程