python读取Excel表格文件的方法
2019-09-02 14:41
2521 查看
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表格文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
您可能感兴趣的文章:
相关文章推荐
- python读取Excel表格文件
- 使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法
- Python导出数据到Excel可读取的CSV文件的方法
- Python使用xlrd读取Excel格式文件的方法
- python读取excel文件的三种方法
- Python读取Excel表格,并同时画折线图和柱状图的方法
- Python导出数据到Excel可读取的CSV文件的方法
- poi读取Excel时日期为数字 的解决方法 转载 2017年12月14日 10:31:14 标签:poi /excel /java 19 在使用poi解析Excel文件时,会发现,表格中的日期解析出
- Python使用xlrd读取Excel格式文件的方法
- python3读取excel文件只提取某些行某些列的值方法
- Python实现读取txt文件并转换为excel的方法示例
- python读取excel文件中所有sheet表格:openpyxl模块(二)
- asp.net读取excel文件多种方法
- ASP.NET读取EXCEL文件的三种经典方法
- Python 使用 xlrd 读取 Excel格式文件
- ASP.NET读取EXCEL文件的三种经典方法(转)
- 【python】 读取Excel文件并绘制图表
- ASP.NET读取EXCEL文件的三种经典方法
- Python Excel Tutorial (一):xlrd的安装和读取Excel文件
- 【python】 读取Excel文件并绘制图表