Python .csv转Excle数据(csv数据为空格分割)

#coding:utf-8
import csv
import xlwt
#新建excel文件
myexcel = xlwt.Workbook()
#新建sheet页
mysheet = myexcel.add_sheet("name.csv")

#读取csv文件名集代码
f = open("csvNameList.txt", "r")
line = f.readline()
names=[]
while line != "":
    line = line.strip()
    s = line[:3]
    if s.isalpha():
        s = line[:3]
    else:
        s=line[:2]
    names.append(s)
    line = f.readline()
f.close()

l=0
for name in names:
    fName=name+'.csv'
    #写表头到excle
    mysheet.write(l,0,name)
    for r in range(1,4):
        sheetHead='L'+str(r)
        mysheet.write(l,r,sheetHead)
    mysheet.write(l,4,"rowName1")
    mysheet.write(l,5,"rowName2")
    mysheet.write(l,6,"rowName3")
    mysheet.write(l,7,"rowName4")
    l=l+1
    #打开csv文件
    csvfile = file(fName,"rb")
    #读取文件信息
    reader = csv.reader(csvfile)
    year=18
    #通过循环获取单行信息
    for line in reader:
        mysheet.write(l,0,str(year))
        year=year+1
        r = 1
        #通过双重循环获取单个单元信息
        for i in line:
            left=0 
            right=0
            cnt =0
            dataArr=[]
            sum=0
            for pos in i:
                cnt = cnt+1
                if pos is ' ':
                    right = cnt
                    dataCur=i[left:right]
                    #计算总和and存储数据
                    sum=sum+int(dataCur)
                    dataArr.append(int(dataCur))
                    left=right
                    mysheet.write(l,r,dataCur)
                    r=r+1
            right=cnt+1
            dataCur=i[left:right]
            #计算总和and存储数据
            sum=sum+int(dataCur)
            dataArr.append(int(dataCur))
            mysheet.write(l,r,dataCur)
            r=r+1
            mysheet.write(l,r,sum)
            r=r+1
            for dataElement in dataArr:
                if sum == 0:
                    mysheet.write(l,r,0)
                else:
                    rateCur=float(dataElement)/sum
                    mysheet.write(l,r,rateCur)
                r=r+1
        l=l+1
    mysheet.write(l,0," ")
    l=l+1
#最后保存到excel
myexcel.save("excleName.xls")

你可能感兴趣的:(python,csv,excel)