python操作exel

本文档主要是创建日常使用的exel库函数,具体exel的操作可参考:

https://blog.csdn.net/sinat_28576553/article/details/81275650#%E4%BA%8C%E3%80%81%E4%BD%BF%E7%94%A8xlwt%E6%A8%A1%E5%9D%97%E5%AF%B9%E6%96%87%E4%BB%B6%E8%BF%9B%E8%A1%8C%E5%86%99%E6%93%8D%E4%BD%9C

1、安装支撑包

pip install xlrd

pip install xlutils

2、创建exel的类:

import xlrd                       #导入xlrd库
from xlutils.copy import copy     #导入copy方法,用于修改exel表格内容

class Operate_Exel():                                #定义一个操作exel的类
    def __init__(self,exel_path=None,sheet_ID=None): #初始化函数,方便后续调用
        self.exel_path=exel_path
        self.sheet_ID=sheet_ID
        self.data=self.get_data()                    #初始化使得self.data=self.get_data(),精简代码方便后续调用

    def get_data(self):                              #获得sheet对象
        workbook=xlrd.open_workbook(self.exel_path)
        sheet=workbook.sheet_by_index(self.sheet_ID) #也可以使用sheet_by_name()
        return sheet

    def get_nrows(self):                             #获取行数
        return self.data.nrows

    def get_ncols(self):                             #获取列数
        return self.data.ncols

    def get_cell_value(self,row,col,value):          #获取某一个单元格内容
        self.data.cell_value(row,col,value)

    def get_row_values(self,row):                    #获取一整行内容
        self.data.row_values(row)

    def get_col_values(self,col):                    #获取一整列内容
        self.data.col_values(col)

    def change_data(self,row,col,value):            #某一单元格修改数据,实际使用中,修改会比创建多,所以不是有xlwt
        old=xlrd.open_workbook(self.exel_path)
        new=copy(old)                                #新的exel对象
        write=new.get_sheet(self.sheet_ID)           #获取需要修改的sheet页
        write.write(row,col,value)                   #写入数据
        new.save(self.exel_path)                     #

猜你喜欢

转载自www.cnblogs.com/fxqtang/p/10557194.html