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()

    案例截图:

  • 相关阅读:
    svnserve 配置
    JDBC与JTA的区别
    Redhat E5上安装Subversion 1.6详解
    CentOS5.3 编译 mod_jk 1.2.15 链接器 整合apache httpd 和 tomcat
    Linux对逻辑卷的创建与管理
    spring 包的解释
    vue.js之router详解(一)
    Ubuntu12.10 高速全自动配置bash脚本
    PHP execl导出/展示
    有关Linux下的一些配置
  • 原文地址:https://www.cnblogs.com/peterpan0707007/p/8805249.html
Copyright © 2011-2022 走看看