python讀取Excel表格文件


python讀取Excel表格文件,例如獲取這個文件的數據

 

 

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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM