python 追加excel内容

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import xlwt
import xlrd
import xlutils
from xlutils.copy import copy
import MySQLdb
import os
os.chdir("E:\work") 


def add_class():
    wbk = xlwt.Workbook()
    workbook = xlrd.open_workbook(r'E:\work\k-means_result.csv') #r_xls
    sheet1 = workbook.sheet_by_index(0) #r_sheet
    rows = sheet1.row_values(0) 
    cols = sheet1.col_values(20)
    #print len(cols)
    print cols[1]
    print type(cols[1])
    print type('聚类-1')
    #rows_num = sheet1.nrows #50054
    w_xls = copy(workbook)
    sheet_write = w_xls.get_sheet(0)
    sheet_write.write(0,21,'class')  
    for i in range(1, len(cols)):
        if cols[i] == u'聚类-1':
            sheet_write.write(i,21,1)
        if cols[i] == u'聚类-2' or cols[i] == u'聚类-4' or cols[i] == u'聚类-6' or cols[i] == u'聚类-11':
            sheet_write.write(i,21,2)
        if cols[i] == u'聚类-3' or cols[i] == u'聚类-5':
            sheet_write.write(i,21,3)   
        if cols[i] == u'聚类-8':
            sheet_write.write(i,21,4)
        if cols[i] == u'聚类-9' or cols[i] == u'聚类-10':
            sheet_write.write(i,21,5)
    w_xls.save('k-means_result.csv')


if __name__ == "__main__":
    print "Begin"
    add_class()
    print "Over"

今天需要根据用户购买情况的聚类结果把11个类合并为5个类,并在excel表里给出类别标签。经过百度发现python操作excel追加内容只能用xlutils库,大体思想是复制以前的表,增加内容后再写入excel。在此过程中还遇到了比较unicode和str的问题,最后的解决方法是都转换为unicode。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值