python读写excel文件

来源:互联网 发布:淘宝买csgo怎么下载 编辑:程序博客网 时间:2024/05/19 13:18

安装xlrd、xlwt、xlutils

#coding=utf-8import xlrd import xlwt;  import sys, getoptfrom xlutils.copy import copy;  class Excel:        def __init__(self,fileName):        self.bookold = xlrd.open_workbook(fileName)                    self.book=copy(self.bookold)                                def insert_merchant_number(self):                sheet=self.bookold.sheet_by_index(0)                            nrows = sheet.nrows                ncols = sheet.ncols        sheetnew=self.book.get_sheet(0);                  cnt=0        flag=0           merchant_number=""             for r in range(0,nrows-1):            cellvalue=sheet.cell_value(r,0)                                      if cellvalue==u"特约单位编号/部门编号:":                 merchant_number=sheet.cell_value(r,1)                                   merchant_number=int(merchant_number)                 merchant_number=str(merchant_number)                 print u"商户号"+merchant_number                                  flag=1                             if flag==1 and cellvalue!=u"特约单位编号/部门编号:" and cellvalue!=u"特约单位合计":                mer=sheet.cell_value(r,0)                                  mer=int(mer)                                                              print "value "+str(mer)                #mer=str(mer)                                 mer=str(merchant_number)                info=u"写入数据: "                print info+mer                sheetnew.write(r,0,mer);            if cellvalue==u"特约单位合计":                  flag=0                                             def save_excle_file(self,fileName):                    self.book.save(fileName)def main():    opts, args = getopt.getopt(sys.argv[1:], "hi:o:",["ifile=","ofile="])    input_file=""    output_file=""    mer=""    for op, value in opts:        if op == "-i":            input_file = value        elif op == "-o":            output_file = value                elif op == "-h":                        sys.exit()    excel=Excel(input_file)        excel.insert_merchant_number()    excel.save_excle_file(output_file)if __name__=="__main__":    main()

代码例子

原创粉丝点击