如何快速在Python中打开Excel文件?
我现在在用 PyExcelerator 来读取Excel文件,但速度慢得让人受不了。因为我经常需要打开超过100MB的Excel文件,光是加载一个文件就要花超过二十分钟。
我需要的功能有:
- 打开Excel文件,选择特定的表格,然后把它们加载到字典或列表对象里。
- 有时候:选择特定的列,只加载那些在特定列中有特定值的整行数据。
- 读取带密码保护的Excel文件。
我现在用的代码是:
book = pyExcelerator.parse_xls(filepath)
parsed_dictionary = defaultdict(lambda: '', book[0][1])
number_of_columns = 44
result_list = []
number_of_rows = 500000
for i in range(0, number_of_rows):
ok = False
result_list.append([])
for h in range(0, number_of_columns):
item = parsed_dictionary[i,h]
if type(item) is StringType or type(item) is UnicodeType:
item = item.replace("\t","").strip()
result_list[i].append(item)
if item != '':
ok = True
if not ok:
break
有没有什么建议?
5 个回答
1
你可以尝试一次性预先分配好列表的大小,而不是像这样一个一个地添加项目:(一次性分配一大块内存通常比多次分配小块内存要快)
book = pyExcelerator.parse_xls(filepath)
parsed_dictionary = defaultdict(lambda: '', book[0][1])
number_of_columns = 44
number_of_rows = 500000
result_list = [] * number_of_rows
for i in range(0, number_of_rows):
ok = False
#result_list.append([])
for h in range(0, number_of_columns):
item = parsed_dictionary[i,h]
if type(item) is StringType or type(item) is UnicodeType:
item = item.replace("\t","").strip()
result_list[i].append(item)
if item != '':
ok = True
if not ok:
break
如果这样做能明显提高性能,你还可以尝试为每个列表项预先分配列的数量,然后通过索引来赋值,而不是一个一个地添加值。下面的代码片段展示了如何在一条语句中创建一个10x10的二维列表,并且初始值都是0:
L = [[0] * 10 for i in range(10)]
所以把它放到你的代码里,可能会像这样工作:
book = pyExcelerator.parse_xls(filepath)
parsed_dictionary = defaultdict(lambda: '', book[0][1])
number_of_columns = 44
number_of_rows = 500000
result_list = [[''] * number_of_rows for x in range(number_of_columns)]
for i in range(0, number_of_rows):
ok = False
#result_list.append([])
for h in range(0, number_of_columns):
item = parsed_dictionary[i,h]
if type(item) is StringType or type(item) is UnicodeType:
item = item.replace("\t","").strip()
result_list[i,h] = item
if item != '':
ok = True
if not ok:
break
6
pyExcelerator这个工具似乎已经不再维护了。如果你想写xls格式的文件,可以使用xlwt,这个工具是pyExcelerator的一个改进版,修复了很多bug,还增加了许多新功能。不过,pyExcelerator里很基础的读取xls文件的功能在xlwt里被去掉了。如果你需要读取xls文件,可以用xlrd。
如果你加载一个100MB的xls文件需要20分钟,那可能是因为你用的电脑比较慢,或者电脑的内存很小,或者你用的是旧版本的Python。
无论是pyExcelerator还是xlrd,都不能读取有密码保护的文件。
这里有一个链接,介绍了xlrd和xlwt。
声明:我是xlrd的作者,也是xlwt的维护者。