300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python3遍历电子表格_用openpyxl遍历excel表格

python3遍历电子表格_用openpyxl遍历excel表格

时间:2019-03-19 05:55:04

相关推荐

python3遍历电子表格_用openpyxl遍历excel表格

Python的openpyxl模块,提供了对excel表格的读写操作接口。本文介绍使用openpyxl来遍历excel表格。

openpyxl支持Excel xlsx/xlsm/xltx/xltm files,官网:https://openpyxl.readthedocs.io

表格就是由一些行和列的组成,按照程序员的思路,遍历一个表格,就是一个两重循环。不过,在遍历excel表格的时候,程序员会面对一个问题,即表格的有效内容,是从第几行开始,到第几行结束,对于列也是这个问题,程序预先不应该知道开始的列和结束的列,而且如果中间还有空行和空列,就更麻烦了。

openpyxl帮助我们解决了这个问题,看代码:

from openpyxl import load_workbook

wb = load_workbook(filename='large_file.xlsx', read_only=True)

ws = wb['big_data']

for row in ws.rows:

for cell in row:

print(cell.value)

用只读模式打开一个xlsx文件,选择big_data这个sheet,然后就开始遍历,不管开始的行列和中间的空行列。语义非常自然优美,延续了python的优良传统。

关于excel表格的开始行和结束列,我们可以深入一点点。openpyxl官网有一段关于这个问题的介绍:

Worksheet dimensions

Read-only mode relies on applications and libraries that created the file providing correct information about the worksheets, specifically the used part of it, known as the dimensions. Some applications set this incorrectly. You can check the apparent dimensions of a worksheet using ws.calculate_dimension(). If this returns a range that you know is incorrect, say A1:A1 then simply resetting the max_row and max_column attributes should allow you to work with the file:

ws.reset_dimensions()

打开excel表格后,检查worksheet dimensions,如果不对,就reset,openpyxl自动寻找开始行和结束列。所以,应用程序可以总是调用一次reset_dimensions函数,来确保后面代码的正确执行。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。