zoukankan      html  css  js  c++  java
  • 【Python】Excel数据处理

    1、环境准备

    > python2.7

    > xlrd,xlwt模块下载与安装,前者用来读取excel文件,后者用来写入excel文件

    2、实战案例

    案例场景:

    > excel1中包含某个市所有客户名称(可能有重复的)

    > excel2中包含某个省所有客户名称(无重复)、起始IP地址和终止IP地址

    案例目的:

    根据excel1中客户名称到excel2中取出对应IP地址范围,要求最终汇总到一个新的excel文件中,包含客户名称和IP地址范围,

    IP地址范围格式要求:如起始和终止IP相等,则以/32结尾,否则以短线连接两个地址

    案例脚本:

    #coding:utf-8
    
    import sys
    import xlrd
    import xlwt
    import csv
    
    #存储客户名称
    list=[]
    
    def readexcel():
        file=sys.argv[1]
        print file
        workbook=xlrd.open_workbook(file)
        sheet1=workbook.sheet_by_index(0)
        col=0
        while col<sheet1.ncols:
            if '客户名称' in sheet1.cell(0,col).value.encode('utf-8'):
                row=1
                while row<sheet1.nrows:
                    tmp=sheet1.cell(row,col).value.encode('gbk')
                    #去掉重复行
                    if tmp not in list:
                        list.append(tmp)
                    row+=1
            col+=1
        write_excel(list)
            
    #匹配结果输出客户名称、处理后的地址
    def write_excel(u_list):
        file=sys.argv[2]
        filename=sys.argv[1].replace('.xlsx','')+'_new.csv'
        workbook=xlrd.open_workbook(file)
        sheet1=workbook.sheet_by_index(0)
        col=0
        while col<sheet1.ncols:
            if '用户名称' == sheet1.cell(0,col).value.encode('utf-8'):
                row=1
                while row<sheet1.nrows:        
                    uname=sheet1.cell(row,col).value.encode('gbk')
                    for u in u_list:
                        if u == uname:
                            print uname+'	'+sheet1.cell(row,0).value.encode('gbk')
                            with open(filename,'ab') as fw:
                                csv_file=csv.writer(fw,dialect='excel')
                                new_row=[uname,sheet1.cell(row,0).value.encode('gbk')]
                                csv_file.writerow(new_row)
                    row+=1
            col+=1
    if __name__=='__main__':
        readexcel()

    案例截图:

  • 相关阅读:
    正则表达式
    python 模块和包
    python面向对象 : 反射和内置方法
    python面向对象 : 属性, 类方法, 静态方法
    python面向对象 : 抽象类(接口类),多态,封装(私有制封装)
    python面向对象 : 继承
    python面向对象:类空间,对象空间, 组合
    python: 面向对象:类和对象调用类中的变量和方法
    lamda匿名函数(与sorted(),filter(),map() 一起用), 递归函数, 二分查找
    python的各种库的用法
  • 原文地址:https://www.cnblogs.com/peterpan0707007/p/8805249.html
Copyright © 2011-2022 走看看