我希望确定在openpyxl返回的merged_cells集合中是否找到工作表中的单元格。
merged_cells范围如下所示(VSCode调试器):
我有单元格引用J31
-在此集合中可以找到。如果在true
集合中找到该单元格,我该如何编写一个返回merged_cells.ranges
的函数?
答案 0 :(得分:1)
<table>
<col>
<colgroup span="2"></colgroup>
<colgroup span="2"></colgroup>
<tr>
<td rowspan="2"></td>
<th colspan="2" scope="colgroup">Mars</th>
<th colspan="2" scope="colgroup">Venus</th>
</tr>
<tr>
<th scope="col">Produced</th>
<th scope="col">Sold</th>
<th scope="col">Produced</th>
<th scope="col">Sold</th>
</tr>
<tr>
<th scope="row">Teddy Bears</th>
<td>50,000</td>
<td>30,000</td>
<td>100,000</td>
<td>80,000</td>
</tr>
<tr>
<th scope="row">Board Games</th>
<td>10,000</td>
<td>5,000</td>
<td>12,000</td>
<td>9,000</td>
</tr>
</table>
^^ merged_range ^^类型必须为openpyxl.worksheet.cell_range
答案 1 :(得分:0)
在D.Banakh的答案(+1)之前,尝试类似的操作(基于我为别人写的先前示例,因为您的问题所涉及的内容很少):
for cell in ws.merged_cells.ranges:
#print(cellRef +' ==> '+ str(cell.min_row) +'/'+ str(cell.max_row) +'/'+ str(cell.min_col) +'/'+ str(cell.max_col))
if (int(cell.min_row) <= int(row) <= int(cell.max_row)) and (int(cell.min_col) <= int(col) <= int(cell.max_col)):
print('Cell ' +cellRef+ ' is a merged cell')
import re
cellBorders = fnGetCellBorders(ws, cellRef)
if ('T' in cellBorders) or ('L' in cellBorders) or ('R' in cellBorders) or ('B' in cellBorders) or ('M' in cellBorders):
print('Cell has border *OR* is a merged cell and borders cannot be checked')
def getCellBorders(ws, cellRef):
tmp = ws[cellRef].border
brdrs = ''
if tmp.top.style is not None: brdrs += 'T'
if tmp.left.style is not None: brdrs += 'L'
if tmp.right.style is not None: brdrs += 'R'
if tmp.bottom.style is not None: brdrs += 'B'
if (brdrs == '') and ('condTableTopLeftCell' in refs):
if fnIsCellWithinMergedRange(ws, cellRef): brdrs = 'M'
return brdrs
def fnIsCellWithinMergedRange(ws, cellRef):
ans = False
col = fnAlphaToNum(re.sub('[^A-Z]', '', cellRef))
row = re.sub('[^0-9]', '', cellRef)
for cell in ws.merged_cells.ranges:
if (int(cell.min_row) <= int(row) <= int(cell.max_row)) and (int(cell.min_col) <= int(col) <= int(cell.max_col)):
ans = True
return ans
def fnAlphaToNum(ltr):
ab = ["MT", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
return ab.index(ltr)
参考文献:
OpenPyXL - How to query cell borders?
How to detect merged cells in excel with openpyxl
https://bitbucket.org/openpyxl/openpyxl/issues/911/borders-on-merged-cells-are-not-preserved