简体   繁体   English

即使没有,Openpyxl 也能找到合并的单元格

[英]Openpyxl finds merged cells even though there are none

I'm handling excels in my python script and get the following error:我在我的 python 脚本中处理 excels 并收到以下错误:

    Traceback (most recent call last):
  File "script_consolidateExcels_v3.py", line 134, in <module>
    colNum = findColOfCell(ws, "xxx", 1)
  File "script_consolidateExcels_v3.py", line 28, in findColOfCell
    if worksheet.cell(row=inRow, column=k).value == val:
AttributeError: 'MergedCell' object has no attribute 'value'

The excel file initially had merged cells, but I unmerged everything using Microsoft Excel, yet this error still pops up. excel文件最初合并了单元格,但我使用Microsoft Excel取消了所有内容的合并,但仍然弹出此错误。 I even tried ws.unmerge_cells(), but with no help.我什至尝试过 ws.unmerge_cells(),但没有任何帮助。 (Weirdly enough, at first I wrote and run the script on a windows laptop and this error did not pop up... I sent the script to my mac, and now I get this error... (I can't access the windows laptop currently)) (奇怪的是,起初我在 Windows 笔记本电脑上编写并运行脚本,但没有弹出此错误......我将脚本发送到我的 mac,现在我收到此错误......(我无法访问目前 Windows 笔记本电脑))

Here is the problematic part:这是有问题的部分:

def findColOfCell(worksheet, val, inRow, startCol=1):
    i = 0
    k = startCol
    while i == 0:
        if worksheet.cell(row=inRow, column=k).value == val:
            i = 1
            # here = ord(worksheet.cell(row=inRow, column=k).column)-64 # convert column letter to number
            here = worksheet.cell(row=inRow, column=k).column
        else: k += 1
    return here

If you are merging 3 cells say (1,1) (1,2) and (1,3)如果要合并 3 个单元格,请说 (1,1) (1,2) 和 (1,3)

sheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=3)

In this case, cell (1,2) and (1,3) will no longer have attribute 'value'.在这种情况下,单元格 (1,2) 和 (1,3) 将不再具有属性“值”。

You can only assign value to (1,1) as the cell (1,2) and (1,3) does not exist anymore.您只能为 (1,1) 赋值,因为单元格 (1,2) 和 (1,3) 不再存在。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM