openpyxl模块的基本使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
“”"
用读取文件的方式直接读取excel,拿不到想要的数据
excel三大对象:
工作薄 workbook
表单 sheet
格子 cell
“”"
1、通过openpyxl来读取excel文件
import openpyxl
1.1 读取excel文件,返回一个workbook文件
case = openpyxl.load_workbook("case.xlsx")
1.2 选取workbook中的sheet
case1 = case["case1"]
1.3读取表单的内容
1.3.1设置cell中的行和列cell(row,column).value
case_values = case1.cell(row=2, column=2).value
print(case_values)
2、通过openpyxl写入到excel文件
2.1 读取excel文件,返回一个workbook文件
case = openpyxl.load_workbook("case.xlsx")
2.2 选取workbook中的sheet
case1 = case["case1"]
2.3 写入内容
case_values2 = case1.cell(row=5, column=2, value="测试测试")
case_values3 = case1.cell(row=5, column=3).value = "第二种写入方式"
2.4 保存文件
注意点保存时要用workbook的变量来保存
case.save("case.xlsx")
3 消息晋级知识
import openpyxl
3.1 excel文件的读取
workbook = openpyxl.load_workbook("case.xlsx")
sheet1 = workbook["case1"]
row123 = sheet1.rows
3.2每一行的数据会放在一组元组中
row123_list = list(row123)
print(row123_list)
"""
[
(<Cell 'case1'.A1>, <Cell 'case1'.B1>, <Cell 'case1'.C1>, <Cell 'case1'.D1>, <Cell 'case1'.E1>),
(<Cell 'case1'.A2>,<Cell 'case1'.B2>, <Cell 'case1'.C2>, <Cell 'case1'.D2>, <Cell 'case1'.E2>),
(<Cell 'case1'.A3>, <Cell 'case1'.B3>, <Cell 'case1'.C3>, <Cell 'case1'.D3>, <Cell 'case1'.E3>),
(<Cell 'case1'.A4>, <Cell 'case1'.B4>, <Cell 'case1'.C4>, <Cell 'case1'.D4>, <Cell 'case1'.E4>),
(<Cell 'case1'.A5>, <Cell 'case1'.B5>, <Cell 'case1'.C5>, <Cell 'case1'.D5>, <Cell 'case1'.E5>)
]
"""
3.3获取每组元组的value值
3.3.1首先元组是放在列表中的,然后取出一组元组来举例
row2 = row123_list[2]
3.3.2 元组中的元素用for循环在取出来
for i in row2:
# print(i)
"""
<Cell 'case1'.A3>
<Cell 'case1'.B3>
<Cell 'case1'.C3>
<Cell 'case1'.D3>
<Cell 'case1'.E3>
"""
# 将取出的元组转换为value,即在元素后面加上.value
# print(i.value)
# 于是你就得到了它:
"""
2
此账号以存在
("Nicholas", "1234567", "1234567")
{"code": 0, "msg": "此账号以存在"}
None
"""
3.4 同理将columns替换rows,重复上述操作,获取每列的内容
columns = sheet1.columns
columns_list = list(columns)
columns_values = []
columns_values1 = []
for columns_tuple in columns_list:
columns_values = [columns_value.value for columns_value in columns_tuple]
columns_values1.append(columns_values)
# print(columns_values1)
获取表单行数
print(sheet1.max_row)
获取表单列数
print(sheet1.max_column)