在python脚本中指定文件名来打开Excel工作簿
问题描述:
这是一个非常愚蠢的问题,但我试图学习python和我被卡在使用xlrd读取Excel文件的例子。 我在网上发现了这个脚本,但我无法弄清楚我应该在哪里填写我的文件名以使其打开。在python脚本中指定文件名来打开Excel工作簿
from future import print_function from os.path import join, dirname, abspath, isfile from collections import Counter import xlrd from xlrd.sheet import ctype_textdef 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_sheetsdf
答
您可以输入文件名:
-
当你调用该函数
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
答
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')
你想后,这个目标是Excel工作表对象xl_sheet_obj
什么。
谢谢,但还是不起作用。我在同一个文件夹中有excel文件,我是否需要指定完整路径nevertheles? –
你不需要,什么是错误输出? –
好吧,它说的语法是错误的。我删除了'从'不“,现在它的工作,谢谢! –