मैंने xlrd, pandas, openpyxl और ऐसी अन्य लाइब्रेरीज़ को आज़माया है और ये सभी घातीय समय लेती हैं क्योंकि फ़ाइल का आकार बढ़ने पर यह पूरी फ़ाइल को पढ़ता है। ऊपर वर्णित अन्य समाधान जहां उन्होंने 'on_demand' का उपयोग किया, मेरे लिए काम नहीं किया। यदि आप प्रारंभ में केवल शीट नाम प्राप्त करना चाहते हैं, तो निम्न फ़ंक्शन xlsx फ़ाइलों के लिए काम करता है।
def get_sheet_details(file_path):
sheets = []
file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
# Make a temporary directory with the file name
directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
os.mkdir(directory_to_extract_to)
# Extract the xlsx file as it is just a zip file
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close()
# Open the workbook.xml which is very light and only has meta data, get sheets from it
path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
with open(path_to_workbook, 'r') as f:
xml = f.read()
dictionary = xmltodict.parse(xml)
for sheet in dictionary['workbook']['sheets']['sheet']:
sheet_details = {
'id': sheet['@sheetId'],
'name': sheet['@name']
}
sheets.append(sheet_details)
# Delete the extracted files directory
shutil.rmtree(directory_to_extract_to)
return sheets
चूंकि सभी xlsx मूल रूप से ज़िपित फ़ाइलें हैं, हम अंतर्निहित xml डेटा को निकालते हैं और कार्यपुस्तिका से सीधे शीट नामों को पढ़ते हैं जो लाइब्रेरी फ़ंक्शन की तुलना में एक सेकंड का एक अंश लेता है।
बेंचमार्किंग: (4 शीटों के साथ 6mb xlsx फ़ाइल पर)
पंडों, xlrd: 12 सेकंड में
ओपनपीएक्सएल: 24 सेकंड
प्रस्तावित विधि: 0.4 सेकंड
चूँकि मेरी आवश्यकता सिर्फ शीट के नामों को पढ़ने की थी, इसलिए पूरे समय पढ़ने का अनावश्यक ओवरहेड मुझे परेशान कर रहा था इसलिए मैंने इस मार्ग को छोड़ दिया।
ExcelFile
? यह भी कहें कि मैं चादरों की सूची देखता हूं और उनमें से एन को लोड करने का फैसला करता हूं, क्या मुझेread_excel
प्रत्येक शीट के लिए उस बिंदु पर कॉल (नया इंटरफ़ेस) करना चाहिए या छड़ी करनी चाहिएx1.parse
?