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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM