Python操作Excel

前言:

Python操作Excel使用openpyxl模块,python中有好几个与excel相关操作的模块。

  xlrd库:从excel中读取数据,支持xls、xlsx格式。

  xlwt库:对excel进行修改操作,不支持对xlsx格式的修改。

  xlutils库:在xlrd和xlwd中对一个已存在的文件进行修改。

  openpyxl库:主要针对xlsx格式的excel进行读取和编辑。

一、openpyxl模块介绍

  openpyxl模块是一个读写Excel 2010文档的Python库,如果要处理更早格式的Excel文档,需要用到额外的库,openpyxl是一个比较综合的工具,能够同时读取和修改Excel文档。其他很多的与Excel相关的项目基本只支持读或者写Excel一种功能。

二、安装openpyxl模块

  命令行中运行:pip install openpyxl

三、Excel中的三大对象:WorkBook、Sheet、Cell

在excel中主要的操作是在sheet中对数据进行读、写、修改的操作。操作流程如下:

1)生成一个工作薄(workbook)对象,workbook = load_workbook("这里写excel文件路径")。

2)获取某个表单(sheet)对象,sheet = workbook["这里写sheet名字"]。

3)在表单对象中的单元格(cell)中读、写、修改数据。

源码如下: 

 1 from openpyxl import load_workbook  #引入库
 2 
 3 # 1.生成一个工作薄对象
 4 workbook = load_workbook('testdata.xlsx')
 5 
 6 #获取指定的表单
 7 sheet = workbook['Sheet1']
 8 
 9 # 获取第一个表单
10 ws = workbook.active
11 
12 # 读取表单中的数据
13 data = sheet.cell(row=2,column=1).value
14 print(data)
15 
16 # 修改表单中的数据
17 sheet.cell(row=2,column=3).value = 18
18 
19 # 保存数据
20 workbook.save('testdata.xlsx')
21 print('保存成功')
22 
23 #获取总行数
24 print('共有',sheet.max_row,'')
25 print('共有',sheet.max_column,'')
26 
27 # 读取所有的数据
28 # 按行读取
29 for index in range(1,sheet.max_row+1):
30     print('行号',index)
31     for i in range(1,sheet.max_column+1):
32         print('列号:',i,'内容:',sheet.cell(row=index,column=i).value)

 四、读取sheet中所有数据通用类函数,列表嵌套列表 

 from openpyxl import load_workbook
 
 class DoExcel:
     def __init__(self,file_path,sheet_name):
         self.file_path = file_path
         self.wb = load_workbook(file_path)
         self.sheet = self.wb[sheet_name]
   
     # 第一种:列表嵌套列表,缺点:要数每个值的索引
     def do_excel(self):
         maxrow = self.sheet.max_row  #获取最大行
         maxrol = self.sheet.max_column #获取最大列
         test_datas = []  #所有数据
         for i in range(2,maxrow+1):
             single_data = []  #每行数据
             for j in range(1,maxrol+1):
                 new_data = self.sheet.cell(i,j).value
                single_data .append(new_data)
             test_data.append(single_data )
         # print(test_data)
         return test_data  #返回所有数据

if __name__ == '__main__':
    test_data = DoExcel('test_data.xlsx','test_data').do_excel()

 五、读取sheet中所有数据通用类函数,列表嵌套字典

from openpyxl import load_workbook

class DoExcel:
    def __init__(self,file_path,sheet_name):
        self.file_path = file_path
        self.wb = load_workbook(file_path)
        self.sheet = self.wb[sheet_name]

    # 第二种:列表嵌套字典,每一行数据保存在字典里
    def do_excel(self,button,case_id_list):
        maxrow = self.sheet.max_row  #获取最大行
        maxcolumn = self.sheet.max_column  #获取最大列

        # ---获取所有表头,也就是第一行---
        headers = []
        for col in range(1,maxcolumn+1):
            headers.append(self.sheet.cell(1,col).value)

        test_datas = []    #所有数据
        for row in range(2,maxrow+1):
            single_data = {}  #存储单行数据
            for i in range(1,len(headers) + 1):
                single_data[headers[i-1]] = self.sheet.cell(row,i).value
            test_datas.append(single_data)
        print(test_datas)

if __name__ == '__main__':
     test_data = DoExcel('test_data.xlsx','test_data').do_excel()
原文地址:https://www.cnblogs.com/lizhe860/p/9042528.html