【问题标题】:Specify filename in python script to open Excel workbook在 python 脚本中指定文件名以打开 Excel 工作簿
【发布时间】:2017-04-29 13:13:45
【问题描述】:

这是一个非常愚蠢的问题,但我试图学习 python,但我被困在使用 xlrd 读取 Excel 文件的示例中。 我在网上找到了这个脚本,但我不知道我应该在哪里填写我的文件名才能打开它。

未来 导入 print_function
from os.path import join, dirname, abspath, isfile
从集合导入计数器
导入 xlrd
从 xlrd.sheet 导入 ctype_text

def get_excel_sheet_object(fname, idx=0): 如果不是 isfile(fname): print ('文件不存在: ', fname) # 打开工作簿和第一张工作表 xl_workbook = xlrd.open_workbook(fname) xl_sheet = xl_workbook.sheet_by_index(0) print (40 * '-' + 'nRetrieved worksheet: %s' % xl_sheet.name)

return xl_sheetsdf

【问题讨论】:

    标签: python excel xlrd


    【解决方案1】:

    你可以输入文件名:

    • 当你调用函数时

      get_excel_sheet_object("myfile.xlsx")

             OR
      

      fname = "myfile.xlsx"

      get_excel_sheet_object(fname)

    • 你的程序中的原始数据:

      def get_excel_sheet_object(idx=0):
      
            fname = "myfile.xlsx"
      
            if not isfile(fname):
               print ("File doesn't exist: ", fname)
            # Open the workbook and 1st sheet
            xl_workbook = xlrd.open_workbook(fname)
            xl_sheet = xl_workbook.sheet_by_index(0)
            print (40 * '-' + 'nRetrieved worksheet: %s' % xl_sheet.name)
      
            return xl_sheet      
      

    【讨论】:

    • 谢谢,但还是不行。我在同一个文件夹中有excel文件,我需要指定完整路径吗?
    • 嗯,它说语法错误。我从“不要”中删除了 ',它现在可以工作了,谢谢!
    • 太好了,如果对您有帮助,您能接受答案吗?
    【解决方案2】:
    from future import print_function
    from os.path import join, dirname, abspath, isfile
    from collections import Counter
    import xlrd
    from xlrd.sheet import ctype_text   
    
    
    def get_excel_sheet_object(fname, idx=0):
        if not isfile(fname):
            print ('File doesn't exist: ', fname)
                # Open the workbook and 1st sheet
        xl_workbook = xlrd.open_workbook(fname)
        xl_sheet = xl_workbook.sheet_by_index(0)
        print (40 * '-' + 'nRetrieved worksheet: %s' % xl_sheet.name)
    
        return xl_sheet
    
    xl_sheet_obj = get_excel_sheet_object('FILE_NAME_HERE')
    

    使用xl_sheet_obj 做任何你想做的事,之后这个对象就是excel 工作表对象。

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 2014-09-12
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多