当前位置: 移动技术网 > IT编程>脚本编程>Python > python读取Excel表格文件的方法

python读取Excel表格文件的方法

2019年09月06日  | 移动技术网IT编程  | 我要评论

ck沉珂的自残照片,ifocus,姊妹花的双重奏

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)

总结

以上所述是小编给大家介绍的python读取excel表格文件的方法,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网