运营的Python指南 - Python 操作Excel
这是一份写给运营人员的Python指南。本文主要讲述如何使用Python操作Excel。完成Excel的创建,查询和修改操作。
相关代码请参考 https://github.com/RustFisher/python-playground
本文链接:https://www.rustfisher.com/2019/11/05/Python/Python-op-excel_openpyxl_use/
开发工具,环境
- PyCharm - 方便好用的IDE
- Python3
这里默认你的电脑上已经装有python3.x,环境变量已经配置好。
引入openpyxl
这里使用openpyxl库来操作Excel。类似的库还有xlrd。
penpyxl的基础使用方法请参见Python openpyxl 处理Excel使用指南。
pip install openpyxl
数据准备
假定数据来自百度指数,以常见的一些搜索指数为例。给后面的操作准备一些数据,把数据写入Excel中。
创建Workbook对象,获取到当前可用的表格(sheet)。
直接使用append
方法把一行数据追加写入。最后调用Workbook的保存方法,存储数据。
def create_excel_demo(file_path): """ 创建Excel文件,并写入数据 :param file_path: 目标文件路径 :return none """ wb = Workbook() ws = wb.active ws.title = '搜索指数概览' ws.append(['关键词', '整体日均值', '移动日均值', '整体同比', '整体环比', '移动同比', '移动环比']) ws.append(['excel', 27782, 18181, -0.11, -2, 0.21, 0.02]) ws.append(['python', 24267, 8204, 0.27, 0.06, 0.56, 0.01]) ws.append(['文案', 2411, 1690, 0.56, 0.33, 0.91, 0.46]) ws.append(['okr', 1928, 880, 0.38, 0.15, 0.29, 0.09]) ws.append(['kpi', 4212, 2784, 0.21, -0.19, 0.36, -0.22]) wb.save(file_path)
创建出来的表格,示例数据如下
关键词 | 整体日均值 | 移动日均值 | 整体同比 | 整体环比 | 移动同比 | 移动环比 |
---|---|---|---|---|---|---|
excel | 27782 | 18181 | -0.11 | -2 | 0.21 | 0.02 |
python | 24267 | 8204 | 0.27 | 0.06 | 0.56 | 0.01 |
... |
读取数据
访问整个表格的数据