python:选房抽签小工具

1、房间号和姓名写在house_name.xls的house标签页中【注意!名字均不要改动】

2、运行house.py

3、当前同目录下会生成result.xls,即为结果;程序运行过程中不要打开该文件,运行完成后再打开,否则结果无法写入

4、若要重新生成,重新运行house.py即可,结果会重新生成

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, shutil, random, sys, json
from os.path import join
from xlrd import open_workbook
from xlutils.copy import copy

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'


class house:
    def read_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)
        return all_name

    def Write_Excel(self, sheetName, rowIndex, lineIndex, content):
        """
        - rowIndex:行
        - lineIndex:列
        """
        if not os.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)

    def random_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 in xrange(length):
            print i
            print namelist[i]
            self.Write_Excel(sheet_name, i, 1, namelist[i])

    def check_then_create(self, file_path):
        """
        检查文件夹是否存在,不存在则自动创建
        """
        isExists = os.path.exists(file_path)
        if not isExists:
            os.makedirs(file_path)


if __name__ == '__main__':
    obj = house()
    # obj.read_excel(sheet_name)
    obj.random_name(sheet_name)