zoukankan      html  css  js  c++  java
  • 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'	est.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"])
  • 相关阅读:
    构建之法:第二次心得
    构建之法:第一次心得
    tomcat配置限制ip和建立图片服务器
    tomcat8.5优化配置
    java 操作 csv文件
    jsoup教学系列
    (转)js实现倒计时效果(年月日时分秒)
    本地启动tomcat的时候报java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: PermGen space
    使用mybatis执行oracle存储过程
    java 获取web登录者的ip地址
  • 原文地址:https://www.cnblogs.com/vickey-wu/p/6735046.html
Copyright © 2011-2022 走看看