python 读取excel文件封装类

这是一个Python类,用于使用xlrd库读取Excel文件。类定义了read_xlrd方法,允许指定文件名、工作表名或索引、开始行和列以及结束行和列来读取数据。它还包含初始化和析构函数。
摘要由CSDN通过智能技术生成

#!/usr/bin/python  
# coding=utf-8
__author__= 'adengou'
__version__= '0.1.0'
__update__ ='2020.3.17'
import xlrd
'''
           xlrd用法
----------------------------------------------
table = data.sheets()[0]          #通过索引顺序获取

table = data.sheet_by_index(sheet_indx)) #通过索引顺序获取

table = data.sheet_by_name(sheet_name)#通过名称获取

以上三个函数都会返回一个xlrd.sheet.Sheet()对象

names = data.sheet_names()    #返回book中所有工作表的名字

data.sheet_loaded(sheet_name or indx)   # 检查某个sheet是否导入完毕
-----------------------------------------------
nrows = table.nrows  #获取该sheet中的有效行数

table.row(rowx)  #返回由该行中所有的单元格对象组成的列表

table.row_slice(rowx)  #返回由该列中所有的单元格对象组成的列表

table.row_types(rowx, start_colx=0, end_colx=None)    #返回由该行中所有单元格的数据类型组成的列表

table.row_values(rowx, start_colx=0, end_colx=None)   #返回由该行中所有单元格的数据组成的列表

table.row_len(rowx) #返回该列的有效单元格长度
---------------------------------------------
ncols = tablencols = table.ncols   #获取列表的有效列数

table.col(colx, start_rowx=0, end_rowx=None)  #返回由该列中所有的单元格对象组成的列表

table.col_slice(colx, start_rowx=0, end_rowx=None)  #返回由该列中所有的单元格对象组成的列表

table.col_types(colx, start_rowx=0, end_rowx=None)    #返回由该列中所有单元格的数据类型组成的列表

table.col_values(colx, start_rowx=0, end_rowx=None)   #返回由该列中所有单元格的数据组成的列表
------------------------------------------------
table.cell(rowx,colx)   #返回单元格对象

table.cell_type(rowx,colx)    #返回单元格中的数据类型

table.cell_value(rowx,colx)   #返回单元格中的数据

table.cell_xf_index(rowx, colx)   # 暂时还没有搞懂

''' 
###构建类
class readExcel:
####初始化变量 
    def __init__(self):
        self.list =[]
        
        ####析构函数
    def __del__(self):
        
        self.list =None
        
    def read_xlrd(self,excelFile,sheetNameOrIndex,startRows=0,startCols=0,endRows=0,endCols=0):
        #读取Excle文件,excelFile为文件名,
        #sheetNameOrIndex为工作表名或者工作表索引号
        #startRows开始行号(下标从0开始)
        #startCols开始列号(下标从0开始)
        #endRows结束行号(默认为0,读取整个行)
        #endCols结束列号,(默认为0,读取整列)
        

        # 打开文件
        data = xlrd.open_workbook(excelFile)
        # 查看工作表
        #data.sheet_names()
        print("sheets:" + str(data.sheet_names()))

        # 通过文件名获得工作表,获取工作表1
        # sheetType =isinstance(sheetNameOrIndex,str)
        # sheetType=type(sheetNameOrIndex)
        # print(sheetType)
        if(isinstance(sheetNameOrIndex,str)):
            table = data.sheet_by_name(sheetNameOrIndex)
        elif(isinstance(sheetNameOrIndex,int)):
            table = data.sheet_by_index(sheetNameOrIndex)
        else:
            print("表名或表索引错误")
            return ""
        #print(table)
        # 打印data.sheet_names()可发现,返回的值为一个列表,
        # 通过对列表索引操作获得工作表1
        # table = data.sheet_by_index(0)

        # 获取行数和列数
        # 行数:table.nrows
        # 列数:table.ncols
        #print("总行数:" + str(table.nrows))
        #print("总列数:" + str(table.ncols))

        # 获取整行的值 和整列的值,返回的结果为数组
        # 整行值:table.row_values(start,end)
        # 整列值:table.col_values(start,end)
        # 参数 start 为从第几个开始打印,
        # end为打印到那个位置结束,默认为none
        #print("整行值:" + str(table.row_values(0)))
        #print("整列值:" + str(table.col_values(1)))

        # 获取某个单元格的值,例如获取B3单元格值
        #cel_B3 = table.cell(3,2).value
        #print("第三行第二列的值:" + cel_B3)

        if(endRows == 0):
            endRows = table.nrows
        if(endCols==0):
            endCols = table.ncols
            
         
        for i in  range(startRows,endRows):
            
            for j in range(startCols,endCols):
               print(table.cell(i,j).value)       
            print("______________________________________________________")
            
                
              
    
if __name__ == '__main__':
    rex =readExcel()
    rex.read_xlrd("lgb.xlsx","Sheet1",3,1)
 

以下是一个简单的 Python Excel 文件读写操作的封装示例: ```python import pandas as pd class ExcelFile: def __init__(self, file_path): self.file_path = file_path self.data = None # 读取 Excel 文件 def read_file(self): try: # 使用 pandas 库读取 Excel 文件 self.data = pd.read_excel(self.file_path) except FileNotFoundError: print(f"File {self.file_path} not found.") # 写入 Excel 文件 def write_file(self): try: # 将数据写入到 Excel 文件中 writer = pd.ExcelWriter(self.file_path) self.data.to_excel(writer, index=False) writer.save() print(f"File {self.file_path} saved successfully.") except: print(f"Failed to save file {self.file_path}.") # 测试代码 if __name__ == "__main__": # 创建 ExcelFile 对象 excel_file = ExcelFile("example.xlsx") # 读取 Excel 文件 excel_file.read_file() if excel_file.data is not None: print(excel_file.data) # 写入 Excel 文件 new_data = {"Name": ["John", "Mary", "Peter"], "Age": [30, 25, 40]} df = pd.DataFrame(new_data) excel_file.data = df excel_file.write_file() ``` 在这个示例中,我们定义了一个名为 `ExcelFile` 的,这个封装Excel 文件读取和写入操作。在初始化函数中,我们传入一个文件路径,并将其保存为的属性。`read_file` 函数尝试读取这个文件,并将读取到的数据保存为的属性。`write_file` 函数将的属性中的数据写入到对应的文件中。 在测试代码中,我们首先创建一个 `ExcelFile` 对象,并调用 `read_file` 函数来读取一个名为 `example.xlsx` 的 Excel 文件,并将读取到的数据输出到控制台。然后我们创建一个新的 DataFrame 对象,并将其保存为 `ExcelFile` 对象的属性,最后调用 `write_file` 函数将这个 DataFrame 中的数据写入到一个名为 `example.xlsx` 的 Excel 文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值