OpenPyXL-如何查询单元格边框? [英] OpenPyXL - How to query cell borders?

查看:284
本文介绍了OpenPyXL-如何查询单元格边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python和openpyxl的新手.

New to both python and openpyxl.

编写py脚本来遍历大量Excel工作簿/工作表,并且需要查找通过边框格式标识的某些单元格.

Writing a py script to glom through a ton of Excel workbooks/sheets, and need to find certain cells identified by their border formatting.

我在网上看到了一些有关如何设置单元格边界的示例,但是我需要阅读它们.

I see several examples online of how to set cell borders, but I need to read them.

具体来说,当表中的数据不一致但始终存在表边界时,我希望标识表边界.因此,我需要找到标识单元格:

* top / left borders
* top / right borders
* bottom / left borders
* bottom / right borders

(细边框).每个工作表只有一个这样的表.

(thin borders). There is only one such table per worksheet.

某种行家能给我指出一个代码示例吗?到目前为止,我将提供我的代码,但老实说,我不知道如何开始.我遍历每个工作表的代码是:

Could some kind maven point me to a code sample? I would provide my code thus far, but honestly I have no idea how to begin. My code for looping through each worksheet is:

for row in range(1, ws.max_row, 1):
    for col in range(1, sheet.max_column+1):
        tmp = NumToAlpha(col)
        ref = str(tmp) + str(row)
        hasTopBorder = ws[ref].?????? <=== how do I get a boolean here?
        hasLeftBorder = ws[ref].?????? <=== how do I get a boolean here?
        hasRightBorder = ws[ref].?????? <=== how do I get a boolean here?
        hasBottomBorder = ws[ref].?????? <=== how do I get a boolean here?
        if hasTopBorder==True and hasLeftBorder==True and hasRightBorder==False and hasBottomBorder==False: 
            tableTopLeftCell = tmp + str(row)
        elif hasTopBorder==True and hasLeftBorder==False and hasRightBorder==True and hasBottomBorder==False: 
            tableTopRightCell = tmp + str(row)
        elif hasTopBorder==False and hasLeftBorder==True and hasRightBorder==False and hasBottomBorder==True: 
            tableBottomLeftCell = tmp + str(row)
        elif hasTopBorder==False and hasLeftBorder==False and hasRightBorder==True and hasBottomBorder==True: 
            tableBottomRightCell = tmp + str(row)
        if tableTopLeftCell != "" and tableTopRightCell != "" and tableBottomLeftCell != "" and tableBottomRightCell != "": break
    if tableTopLeftCell != "" and tableTopRightCell != "" and tableBottomLeftCell != "" and tableBottomRightCell != "": break

欢迎/感谢您精简此新手代码的评论/建议.

通过查询像这样的单元格:

By querying a cell like this:

tst = sheet['Q17'].border

我看到我得到了这种类型的结果-但是如何使用它呢?还是将其转换为所需的布尔值?

I see that I get this type of result - but how do I use it? Or convert it into the desired boolean?

推荐答案

确定"Q17"是否有边框:

To identify whether the "Q17" has a border:

from openpyxl.styles.borders import Border, Side

if sheet['Q17'].border.left.style == "thin":
    print("Left side of Cell Q17 have left thin border")

这篇关于OpenPyXL-如何查询单元格边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆