python读取excel表格:支持xlsx和xls表格格式
1.在编译器中导入操作excel的包 ----> xlrd (操作读取excel) (在虚拟坏境运行 pip install xlrd 或在编译环境搜xlrd安装)
2.新建一个测试的excel表格:
3.运行代码实现操作excel:
1. 获取excel中对应的所有sheet:
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
# 获取excel中所有sheet名称
print('所有sheet的名称', exce.sheet_names())
# 获取所有sheets的地址
print(exce.sheets())
# 通过下标去访问某个具体的sheet
print(exce.sheets()[0])
# 通过sheet名获取
print(exce.sheet_by_name('python'))
# 通过下标获取
print(exce.sheet_by_index(0))
执行结果为:
2. 获取sheet中行数和列数:
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
#通过sheet名称获取
sheet1 = exce.sheet_by_name('python')
# 获取sheet中行数和列数
nrows = sheet1.nrows
ncols = sheet1.ncols
print('对应sheet中行数:%d行,列数:%d列'% (nrows, ncols))
运行结果为:
3. 获取sheet中整行或整列的数据(数组):
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
# 通过sheet名称获取
sheet1 = exce.sheet_by_name('python')
# 获取sheet中整行或整列的数据(数组)
# 通过下标获取某一行的数据
row1 = sheet1.row_values(1)
# 通过下标获取某一列的数据
col1 = sheet1.col_values(2)
print('某行的数据:', row1)
print('某列的数据:', col1)
运行的结果为:
4. 获取sheet中某个单元格的数据:
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
# 通过sheet名称获取
sheet1 = exce.sheet_by_name('python')
# 获取sheet中某个单元格的数据
cell_A3 = sheet1.cell(2, 0).value # 第三行第一列
cell_B2 = sheet1.cell(1, 1).value # 第二行第二列
cell_C3 = sheet1.cell(2, 2).value # 第三行第三列
print('第一列第三行:', cell_A3)
print('第二行第二列:', cell_B2)
print('第三行第三列:', cell_C3)
***运行结果为:***
5. 获取单元格数据类型:
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
# 通过sheet名称获取
sheet1 = exce.sheet_by_name('python')
# 获取单元格数据类型
A3_ctype = sheet1.cell(2, 0).ctype # 数字类型
B2_ctype = sheet1.cell(1, 1).ctype # str类型
C3_ctype = sheet1.cell(2, 2).ctype # data类型
print('数字类型:', A3_ctype)
print('str类型:', B2_ctype)
print('data类型:', C3_ctype)
注:ctype:0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
运行结果为:
6. 打印合并行的数据:
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
# 通过sheet名称获取
sheet1 = exce.sheet_by_name('python')
# 第一列,第四 五行的数据
print(sheet1.cell(4, 0).value)
print(sheet1.cell(3, 0).value)
print(sheet1.cell(4, 1).value)
print(sheet1.cell(4, 2).value)
运行的结果为:
7. 日期格式的打印:
# -*- coding: utf-8 -*-
import xlrd
# 打开execl文件
exce = xlrd.open_workbook('C:/Users/admin/Desktop/test.xls')
# 通过sheet名称获取
sheet1 = exce.sheet_by_name('python')
# 处理单元格内容为data格式的数据
print(xlrd.xldate_as_datetime(sheet1.cell(2, 2).value, 0)) # 转换成日期格式
print(xlrd.xldate_as_tuple(sheet1.cell(2, 2).value, 0)) # 返回元组
运行的结果为: