【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+'\t'+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()

案例截图:

 

posted @ 2018-04-12 09:38  Carrypan  阅读(1436)  评论(0编辑  收藏  举报