最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

【已解决】openpyxl代码警告:Using a range string with iter_rows is deprecated. Use ws[range_string]

Python crifan 877浏览 0评论

折腾openpyxl处理excel期间,代码:

<code>for eachCommonRow in ws.iter_rows("A1:L2"):
    logging.debug("eachCommonRow=%s", eachCommonRow)
    for eachCellInRow in eachCommonRow:
        logging.debug("eachCellInRow=%s", eachCellInRow)
        eachCellInRow.style = NamedStyleCommonHeader
</code>

出现警告:

<code>/Users/crifan/Library/Python/2.7/lib/python/site-packages/openpyxl/worksheet/worksheet.py:498: UserWarning: Using a range string with iter_rows is deprecated. Use ws[range_string]
  warn("Using a range string with iter_rows is deprecated. Use ws[range_string]")
</code>

去看了看源码:

/Users/crifan/Library/Python/2.7/lib/python/site-packages/openpyxl/worksheet/worksheet.py

<code>if range_string is not None:
    warn("Using a range string with iter_rows is deprecated. Use ws[range_string]")
    min_col, min_row, max_col, max_row = range_boundaries(range_string.upper())
</code>

好像看懂了,应该是:

<code>ws.iter_rows("A1:L2")
</code>

改为:

<code>ws["A1:L2"]
</code>

去试试

<code>for eachCommonRow in ws["A1:L2"]:
</code>

结果:果然就没有警告了。

【总结】

openpyxl中,之前去循环rows是用:

<code>ws.iter_rows("A1:L2")
</code>

现在已废弃这种写法,建议换成:

<code>ws["A1:L2"]
</code>

后记:

去看了官网教程:

Manipulating a workbook in memory — openpyxl 2.5.3 documentation

发现其实是:

要么:

1.range string的写法:[“XM:YN”],其中X,Y是字母,M,N是数字

<code>cell_range = ws['A1':'C2']
</code>

要么:

ws调用iter_rows时,传递row和col的参数

<code>for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
    for cell in row:
        print(cell)
</code>

两种写法都可以。

转载请注明:在路上 » 【已解决】openpyxl代码警告:Using a range string with iter_rows is deprecated. Use ws[range_string]

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
61 queries in 0.257 seconds, using 18.83MB memory