python基础学习-excel的读写


excel的读写
1、安装第三方库:pip install openpyxl
2、导入第三方库:import openpyxl
3、需要了解excel的三大对象

  • 工作簿:WorkBook
  • 表单:sheet
  • 表格:cell

4、excel-读取数据、写入数据

import openpyxl

# 将文件加载为工作簿对象
wb = openpyxl.load_workbook("data.xlsx")
# 表单:获取表单对象
sh = wb["登录"]
# 获取格子对象
cell = sh.cell(row=1, column=2)

# 获取表格中的值
c1 = cell.value
print(c1)

# 读取表单中最大行数
max_row = sh.max_row

# 读取表单中最大列数
max_column = sh.max_column
print(max_row)
print(max_column)

# 按行读取表单中数据
rows_data = list(sh.rows)
for row_data in rows_data:
    for item in row_data:
        print(item.value)

# 按列读取表单中数据
rows_data = list(sh.columns)
for row_data in rows_data:
    for item in row_data:
        print(item.value)

# 读取第三行的数据
res = list(sh.rows)
print(res[2])

# 读取第二列到第四列的内容
res1 = list(sh.columns)
print(res1[1:4])

# # 往表格中写数据:写入后要保存工作簿,且必须关闭打开的文件才可以写入成功
sh = wb["注册"]
sh.cell(row=1, column=3, value="aaa")
wb.save("data.xlsx")

 

posted @ 2020-08-29 18:13  薄咊-  阅读(98)  评论(0编辑  收藏  举报