#!/usr/bin/env python#-*- coding: utf-8 -*-
importos, shutil, random, sys, jsonfrom os.path importjoinfrom xlrd importopen_workbookfrom xlutils.copy importcopy
default_encoding= 'utf-8'
if sys.getdefaultencoding() !=default_encoding:
stdi, stdo, stde=sys.stdin, sys.stdout, sys.stderr
reload(sys)
sys.setdefaultencoding(default_encoding)
sys.stdin, sys.stdout, sys.stderr=stdi, stdo, stde
url_excel_path= 'house_name.xls'result_excel_path= 'result.xls'sheet_name= 'house'
classhouse:defread_excel(self, sheet_name):
workbook=open_workbook(url_excel_path)#读取sheet1表的内容
sheet1_content =workbook.sheet_by_name(sheet_name)#获取sheet1表中的行数
row_count =sheet1_content.nrows#print row_count
#读取第1列的内容
all_house =sheet1_content.col_values(0)
all_house=json.dumps(all_house)#读取第2列的内容
all_name = sheet1_content.col_values(1)returnall_namedefWrite_Excel(self, sheetName, rowIndex, lineIndex, content):"""- rowIndex:行
- lineIndex:列"""
if notos.path.exists(result_excel_path):print "%s not exists" %result_excel_path
shutil.copy(url_excel_path, result_excel_path)
rowIndex=int(rowIndex)
lineIndex=int(lineIndex)
rb= 'r+w'rb= open_workbook(result_excel_path, 'r')
rbook= open_workbook(result_excel_path, 'w')
wb=copy(rbook)
sheetIndex=rbook.sheet_names().index(sheetName)
wb.get_sheet(int(sheetIndex)).write(int(rowIndex), int(lineIndex), content)
wb.save(result_excel_path)defrandom_name(self, sheet_name):#houselist = self.read_excel(sheet_name)[0]
namelist =self.read_excel(sheet_name)print "name:%s" %namelist#打乱姓名
random.shuffle(namelist)print "new name:%s" %namelist
length=len(namelist)for i inxrange(length):printiprintnamelist[i]
self.Write_Excel(sheet_name, i,1, namelist[i])defcheck_then_create(self, file_path):"""检查文件夹是否存在,不存在则自动创建"""isExists=os.path.exists(file_path)if notisExists:
os.makedirs(file_path)if __name__ == '__main__':
obj=house()#obj.read_excel(sheet_name)
obj.random_name(sheet_name)