知行合一

博客园 首页 新随笔 联系 订阅 管理

现有的Excel分为两种格式:xls(Excel 97-2003)和xlsx(Excel 2007及以上)。
Python处理Excel文件主要是第三方模块库xlrd、xlwt、pyexcel-xls、xluntils和pyExcel-erator,以及win32com和openpyxl模块,此外Pandas中也带有可以读取Excel文件的模块(read_excel)。
基于扩展知识的目的,我们使用xlrd模块读取Excel数据。

首先安装该库,在系统终端命令行输入命令pip install xlrd。

 

 

import xlrd # 导入库
# 打开文件
xlsx = xlrd.open_workbook('demo.xlsx')
# 查看所有sheet列表

print ('All sheets: %s' % xlsx.sheet_names())
print ('===================================') # 内容分割线
# 查看sheet1的数据概况
sheet1 = xlsx.sheets()[0] # 获得第一张sheet,索引从0开始
sheet1_name = sheet1.name # 获得名称
sheet1_cols = sheet1.ncols # 获得列数
sheet1_nrows = sheet1.nrows # 获得行数
print ('Sheet1 Name: %s\nSheet1 cols: %s\nSheet1 rows: %s') % (sheet1_name, sheet1_cols, sheet1_nrows)
print ('===================================') # 内容分割线
# 查看sheet1的特定切片数据
sheet1_nrows4 = sheet1.row_values(4) # 获得第4行数据
sheet1_cols2 = sheet1.col_values(2) # 获得第2列数据
cell23 = sheet1.row(2)[3].value # 查看第3行第4列数据
print ('Row 4: %s\nCol 2: %s\nCell 1: %s\n' % (sheet1_nrows4, sheet1_cols2, cell23))
print ('===================================') # 内容分割线
# 查看sheet1的数据明细

for i in range(sheet1_nrows): # 逐行打印sheet1数据
print (sheet1.row_values(i))
上述代码中,我们先读取一个Excel文件,再查看所有sheet(工作簿)并输出sheet1相关属性信息;然后查看sheet1中特定数据行、列和元素的信息;最后用循环的方式,依次读取每个数据行并打印输出。
以下是代码执行后打印输出的结果:
All sheets: [u'Sheet1']
===================================
Sheet1 Name: Sheet1
Sheet1 cols: 4
Sheet1 rows: 10
===================================
Row 4: [u'431381197408191515', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
Col 2: [u'Create_Time', 42725.0, 42725.0, 42725.0, 42725.0, 42725.0, 42725.0, 42725.0, 42725.0, 42725.0]
Cell 1: 深圳市
===================================
[u'ID_number', u'Status', u'Create_Time', u'Business_City']
[u'431381198109106573', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']

[u'431381198809122734', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'431381197903117478', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'431381197408191515', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'431381197606166011', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'43138119850623339X', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'431381198908223477', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'431381198901176911', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']
[u'43138119870827275X', u'\u6709\u6548', 42725.0, u'\u6df1\u5733\u5e02']

在上述打印输出的内容中,我们发现第二列、第三列、第四列与原始数据不同。第二列和第四列出现“异常”的原因是将中文编码统一转换为了Unicode编码,便于在不同程序间调用;第三列出现“异常”是由于将日期格式转换为了数值格式。
上述操作只是将数据从Excel中读取出来,基于读取的数据转换为数组便可以进行矩阵计算。由于矩阵计算大多是基于数值型数据实现的,因此上述数据将无法适用于大多数科学计算场景,这点需要注意。

posted on 2022-08-19 10:27  callbin  阅读(370)  评论(0编辑  收藏  举报