excel 操作之 xlrd(一)

1. 什么是 xlrd 模块?

  ♦python 操作 excel 主要用到 xlrd 和 xlwt 这两个库,即 xlrd 是读 excel,xlwt 是写 excel 的库。
一、安装 xlrd 模块
pip install  xlrd
二、使用介绍
1、常用单元格中的数据类型

     ♦ 0. empty(空的),1 string(text), 2 number, 3 date, 4 boolean, 5 error, 6 blank(空白表格)

 2、导入模块

import xlrd
 3、打开 Excel 文件读取数据

data = xlrd.open_workbook(filename)# 文件名以及路径,如果路径或者文件名有中文给前面加一个 r 拜师原生字符。

4、常用的函数

# 打开Excel文件读取数据
data = xlrd.open_workbook('a.xlsx')

# 使用技巧
#获取一个工作表
table = data.sheets()[0]                   #通过索引顺序获取
table = data.sheet_by_index(0)             #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')      #通过名称获取
print('打印表',table)

#获取整行和整列的值(数组)
a = table.row_values(0, start_colx=0, end_colx=None)   #开始行,开始列数到最后
b = table.col_values(0, start_rowx=0, end_rowx=None)   #开始列,开始行数到最后
print('打印一行的数据',a)
print('打印一列的数据',b)

# 获取行数和列数
nrows = table.nrows
ncols = table.ncols
print('行数为:',nrows)
print('列数为',ncols)

#循环行列表数据
for i in range(nrows ):
    print ('按打印出表的内容',table.row_values(i))

#单元格
cell_A1 = table.cell(0,0).value
print('打印单个单元格数据',cell_A1)
cell_A2 = table.cell(3,2).value
print('打印单个单元格数据',cell_A2)

#使用行列索引
cell_A1 = table.row(3)[2].value
print('使用行列打印单个单元格数据',cell_A1)
cell_A2 = table.col(2)[3].value
print('使用行列打印单个单元格数据',cell_A2)

# 简单的写入
row, col = 0, 0
ctype=1; value="值"
xf =0
table.put_cell(row, col, ctype, value, xf)
a =table.cell(0,0)
print(a)
print(table)

for x in table.get_rows():
    print(x)

例:

import xlrd

def open_excel(file='a.xlsx'):
    try:
        data=xlrd.open_workbook(file)
        return data
    except Exception as e:
        print(str(e))

# 根据索引获取Excel表格中的数据参数:
# file:Excel文件路径   colname_index:表头列名所在行的索引,by_index:表的索引

def excecl_table_byindex(file = None,colname_index = 0,by_index = 0):
    data = open_excel(file)           #打开excel
    table = data.sheets()[by_index]   #打开sheet
    nrows = table.nrows               #行数
    ncols = table.ncols               #列数
    colnames = table.row_values(colname_index)  #读取行数据
    #print(colnames)
    # row_values(行值:0行)
    res_list = []
    for rownum  in range(1,nrows):   #从1行到最后一行
        row = table.row_values(rownum)  #一行行遍历,list类型
        if row:
            app = {}
            for i in range(len(colnames)):
                app[colnames[i]] = row[i]
                res_list.append(app)
    return res_list  #dict

if __name__ == '__main__':
    excecl_table_byindex(file="D:\\python练习\\xlrd整理\\a.xlsx")
    print(excecl_table_byindex(file = "D:\\python练习\\xlrd整理\\a.xlsx"))