温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python读取excel表数据的方法

发布时间:2020-09-29 16:56:45 来源:亿速云 阅读:883 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关python读取excel表数据的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

python读取excel表数据的方法:首先安装Excel读取数据的库xlrd;然后获取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、最终的运行效果如下:

python读取excel表数据的方法

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表数据的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI