openpyxl三步走
获取work book
获取 work sheet
再然后 获取单元格 进行操作
保存文件
安装OpenpyXl
pip install OpenpyXl
导包方式以下两种都可以
from openpyxl import Workbook
from openpyxl import load_workbook
- from openpyxl import load_workbook
-
- #加载excel,注意路径要与脚本一致
- wb = load_workbook('demo.xlsx')
- #激活excel表
- sheet = wb.active
向工作表中写入数据
- from openpyxl import load_workbook
-
- #加载excel,注意路径要与脚本一致
- wb = load_workbook('demo.xlsx')
- #激活excel表
- sheet = wb.active
-
- #向excel中写入表头
- sheet['a1'] = '姓名'
- sheet['b1'] = '性别'
- sheet['c1'] = '年龄'
-
- #向excel中写入对应的value
- sheet.cell(row=2, column=1).value = '张三'
- sheet.cell(row=2, column=2).value = '男'
- sheet.cell(row=2, column=3).value = 20
-
- wb.save('demo.xlsx')
- print('数据写入成功!')
保存至文件
最保险的保存方式是调用 save 方法保存到指定文件:
wb.save(filename)
结果如下:
向工作表中批量写入数据
- from openpyxl import load_workbook
-
- #加载excel,注意路径要与脚本一致
- wb = load_workbook('lpl.xlsx')
-
- #激活excel表
- sheet = wb.active
-
- #向excel中写入表头
- sheet['a1'] = '上'
- sheet['b1'] = '中'
- sheet['c1'] = '野'
- sheet['d1'] = 'adc'
- sheet['e1'] = '辅助'
-
- data = {
- ('the shy','rookie','xun','lucas','puff'),
- ('Nuguri','tian','Doinb','LWX','Crisp'),
- ('Karsa','369','Knight','Jacklove','zhuo'),
- ('Zoom','Kanavi','Yagao','Loken','Lvmao'),
- ('Garvey','Flora','Yuuki','Karmer','Peace'),
- ('Flandre','JieJie ','Viper','Scout','Meiko'),
- }
-
- for i in data:
- sheet.append(i)
-
- wb.save('lpl.xlsx')
-
- print('数据写入成功!')