Python-xlrd

xlrd是python中读取excel的库,xlwt是python中写入excel的库,xlutils是python中修改excel的库,这三个库的使用方法都是一样的,都是先打开excel,然后对excel进行操作,最后保存excel。下面是xlrd的使用方法。
xlrd的安装:pip install xlrd

1.打开excel

import xlrd
# 打开excel文件读取数据
data = xlrd.open_workbook('test.xlsx')

2.获取excel中的所有sheet

# 获取excel中的所有sheet
sheets = data.sheets()

3.获取sheet中的行数和列数

# 获取sheet中的行数和列数
sheet = sheets[0]
sheet = data.sheet_by_index(0)
sheet = data.sheet_by_name('Sheet1')

nrows = sheet.nrows
ncols = sheet.ncols

4.获取sheet中的所有行和列

# 获取sheet中的所有行和列
rows = sheet.get_rows()
cols = sheet.get_cols()

5.获取sheet中的某一行和某一列

# 获取sheet中的某一行和某一列
row = sheet.row(0)
col = sheet.col(0)

cell_value = sheet.cell_value(0, 0).vlaue

6.获取sheet中的某一行的值和某一列的值

# 获取sheet中的某一行的值和某一列的值
row_values = sheet.row_values(0)
col_values = sheet.col_values(0)

7.获取sheet是否为公式

# 获取sheet是否为公式
cell_type = sheet.cell_type(0, 0)

# 获取sheet中单元格的数据类型
cell_types = sheet.cell(0, 0).ctype
cell_type cell_types
0 empty string
1 string
2 number
3 date
4 boolean
5 error

8.获取sheet中的合并单元格

# 获取sheet中的合并单元格
merged_cells = sheet.merged_cells

9.获取sheet中的行和列的默认宽度和高度

# 获取sheet中的行和列的默认宽度和高度
row_default_height = sheet.row_default_height
col_default_width = sheet.col_default_width

10.替换单元格的值

# 替换单元格的值
sheet.put_cell(0, 0, 1, 'test', 0)

11.筛选出列中的某个值

# 筛选出列中的某个值
col_values = sheet.col_values(0)
col_values = [i for i in col_values if i == 'test']

12.保存excel

# 保存excel
data.save('test.xlsx')

13.获取excel中的所有sheet名

# 获取excel中的所有sheet名
sheet_names = data.sheet_names()
posted @ 2023-05-25 09:34  Fanslyx  阅读(76)  评论(0)    收藏  举报