#!/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。