python xlrd 读取值的问题。

初学python,现在用的 xlrd 来读取 xls 里面的值,只能用坐标来读取,感觉不是很灵活,一旦表需要删减,都要改很多值的坐标地址,现在想灵活点处理,不管添加或者删除表结构 都能获取到值。

我想学习,当用xlrd 遍历表的时候,找到张三了,然后判断是为男性,如果满足2个条件就 返回来分数 该如何实现? 谢谢大家。

 # -*- coding:utf-8 -*-
import win32com.client

class easyExcel:
    def __init__(self, filename=None):
        self.xlApp = win32com.client.Dispatch('Excel.Application')
        if filename:
            self.filename = filename
            self.xlBook = self.xlApp.Workbooks.Open(filename)
        else:
            self.xlBook = self.xlApp.Workbooks.Add()
            self.filename = ''  
    def save(self, newfilename=None):
        if newfilename:
            self.filename = newfilename
            self.xlBook.SaveAs(newfilename)
        else:
            self.xlBook.Save()    
    def close(self):
        self.xlBook.Close(SaveChanges=0)
        del self.xlApp    
    def getRange(self, sheet, row1, col1, row2, col2):
        "return a 2d array (i.e. tuple of tuples)"
        sht = self.xlBook.Worksheets(sheet)
        return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value
    def setRange(self, sheet, leftCol, topRow, data):
        """insert a 2d array starting at given location. 
        Works out the size needed for itself"""
    
        bottomRow = topRow + len(data) - 1
        rightCol = leftCol + len(data[0]) - 1
        sht = self.xlBook.Worksheets(sheet)
        sht.Range(
            sht.Cells(topRow, leftCol), 
            sht.Cells(bottomRow, rightCol)
            ).Value = data

    
#举例,sheet1包含原始记录,现根据条件提取记录,写到sheet2.
if __name__ == "__main__":
    try:
        xls = easyExcel(r'C:\Users\Nan\Desktop\test.xlsx')    
        arr=xls.getRange("Sheet1",2,1,7,3)
        res=[]
        for name,sex,score in arr:
            if name=='张三' and sex=='男':
                res.append((name,sex,score))
        #数组res就包含你想要的数据了.下面这个只是为了证明.
        xls.setRange("Sheet2",1,1,res)
    finally:
        xls.save()
        xls.close()

用牛刀吧..方便快捷生动形象.

温馨提示:答案为网友推荐,仅供参考
相似回答