openpyxl [Python] common library of learning

openpyxl

Role: Operation excel spreadsheet

Documentation: http: //yumos.gitee.io/openpyxl3.0/index.html

Installation: pip install openpyxl


import openpyxl

# 创建一个工作簿(在内存中)
# wb = openpyxl.Workbook()

# 通过 active 属性获取,新建的工作簿默认预先建好的工作表(如果工作簿包含多个工作表,该属性将返回第一个)
# ws = wb.active

# 设置工作表名称
# ws.title = 'New Title'

# 追加创建新的工作表
# ws = wb.create_sheet('Mysheet222')

# # 在最前面插入工作表
# ws = wb.create_sheet('Mysheet2', 0)

# 取出所有工作表名
# print(wb.sheetnames)

# 遍历工作表名
# for sheet in wb:
#     print(sheet.title)

# 加载工作簿
wb = openpyxl.load_workbook('aowei.xlsx')

# 通过工作表名定位工作表
sheet = wb["Sheet"]

# 读取单元格数据
# 参数 row:行  column:列
ce = sheet.cell(row=1, column=1)  # 读取第一行,第一列的数据
print(ce.value)
c = sheet ['A1']
print(c.value)

# 读取某一列数据
# 从第 2 行开始,第一行是表头
for row_idx in range(2, sheet.max_row + 1):
    a_value= sheet["A{}".format(row_idx)].value
	# 乘以 0.9 赋值给下一列
	b_value= a_value * 0.9
    sheet["B{}".format(row_idx)] = b_value
    
# 保存工作表
# wb.save("aowei.xlsx")

# 关闭工作薄
wb.close()

Here Insert Picture Description

Published 146 original articles · won praise 2326 · Views 510,000 +

Guess you like

Origin blog.csdn.net/qq_43901693/article/details/104920883