Python使用Openpyxl库处理Excel数据
前言
excel表中的数据如果是少量的,对其进行简单的修改处理是比较简单的,而涉及多个excel文件的大量的数据比对,并根据数据比对结果进行不同的处理,如此大规模的,处理模式单一的通过人为来处理是相当枯燥且耗费精神的。借助openpyxl库使用python语言可以实现这样的工作。
环境准备
- 配置python环境
- 安装pycharm
- 安装openpyxl库
前两步可参照网上教程。以下主要介绍在pycharm中安装openpyxl
- 点击File-settings

- 选择Python Interpreter

- 搜索openpyxl——Install Package

注:为了使下载更快,可以改为国内的镜像源。如上图所示,点击Manage Repositories

点击”+“添加国内镜像,这里我添加了三个
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学:https://pypi.mirrors.ustc.edu.cn/simple/

openpyxl的使用
打开Excel文档
import openpyxl
wb = openpyxl.load_workbook('test.xlsx')
从Excel中获取Sheet
wb.sheetnames
sheet = wb['Sheet1']
sheet.title
从Sheet中获取单元格
sheet['A1']
sheet.cell(row=1,column=2).value
sheet.max_row
sheet.max_column
简单应用实例
获取Sheet表的第一列的数据
list1=[]
for i in range(1,sheet.max_row,1):
list1.append(sheet.cell(row=i,column=1).value)
newlist1 = list(set(list1))
注:应用方面主要是利用for循环,合理使用python的数据结构进行数据的存储,筛选,更改。更进一步的,通过openpyxl可以实现多个Excel表的之间Sheet的对比和筛查。
|