Python 判断是否存在Excel表

Python 判断是否存在Excel表,无则生成,有则删除重建

 

import os
import xlwt
from openpyxl import workbook


def sheet_method(work_book, add_sheet=[]):
    wk = work_book
    # rename default sheet
    ss_sheet = wk.get_sheet_by_name('Sheet')
    ss_sheet.title = add_sheet[0]

    for i in range(1, len(add_sheet)):
        # add new sheet
        wk.create_sheet(add_sheet[i])

    # switch to active sheet
    sheet_num = wk.get_sheet_names()
    last_sheet = len(sheet_num) - 1
    sheet_index = sheet_num.index(sheet_num[last_sheet])
    wk.active = sheet_index


def create_excel(filename="filename.xlsx", recreate=False, add_sheet=[]):
    """
    Judge whether there is exist appointed Excel file, create it if not exist, otherwise delete and recreate it
    :param filename: 
    :return: 
    """

    # .xls后缀结尾的只能用xlwt模块写,只能写2的16次方即65,535条数据
    # path = os.path.join(os.getcwd()+r'\test.xls')
    # .xlsx的只能用openpyxl模块写,这模块能写2的32次方即4,294,967,296的数据
    path = os.path.join(os.getcwd() + "\\" + filename + ".xlsx")
    p1 = os.path.exists(path)
    if p1:
        if recreate:
            os.remove(path)
            wk = workbook.Workbook()
            sheet_method(wk, add_sheet)
            # save workbook
            wk.save(path)
            print("Had been deleted and recreated " + filename)
        else:
            # error_info = 'Exist ' + filename + ' in path: ' + path\
            #              + " Please use another filename, otherwise the "\
            #              + filename + " file will be override"\
            #              + " if you need override please set recreate as Ture"
            # raise Exception, error_info
            pass
    else:
        # filename = xlwt.Workbook()
        wk = workbook.Workbook()
        sheet_method(wk, add_sheet)
        # save workbook
        wk.save(path)
        # print("you had create " + filename)

create_excel("test2222", recreate=True, add_sheet=["rebuild3", "rebuild4"])

 

posted @ 2017-04-19 19:06  随便了888  阅读(14859)  评论(0编辑  收藏  举报