python操作excel的讀、計算、寫----xlrd、copy


import  xlrd
from xlutils.copy import copy
class ExcelUtil:
    def __init__(self,excel_path=None,index=None):
        if excel_path == None:
            excel_path = 'C:\\Users\\Administrator\\Desktop\\ooo.xls'
        if index == None:
            index = 0
        self.data = xlrd.open_workbook(excel_path)
        self.table = self.data.sheets()[index]
        self.read_value = self.data
        self.write_data = copy(self.data)
    #按照每行的List,添加到一個大的List里面
    def get_data(self):
        ddt_list = []
        rows = self.get_lines()
        if rows!=None:
            for i in range(rows):
                col = self.table.row_values(i)
                ddt_list.append(col)
            return ddt_list
        return None
    def get_lines(self):#獲取excel的行數
        rows = self.table.nrows
        if rows>=1:
            return rows
        return None
    def get_col_value(self,row,col):#獲取單元格的數據
        if self.get_lines()>row:
            data = self.table.cell(row,col).value
            return data
        return None
    def write_value(self,row,value):#寫入數據
        self.write_data.get_sheet(0).write(row,2,value)  #2是要寫入的列數,從0開始的
        self.write_data.save('C:\\Users\\Administrator\\Desktop\\ooo.xls')
if __name__ == '__main__':
    a = ExcelUtil()
    zonghanshu=a.get_lines()
    for i in range(1,zonghanshu):
        A = str(a.get_col_value(i,1))
        suanfa = str(a.get_col_value(i,0)).replace('操作貨量',A) #讀取excel算法,替換其中的參數。
        jieguo=round(eval(suanfa),2)#round 結果保留兩位小數,eval 計算
        a.write_value(i,jieguo)  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM