簡體   English   中英

使用openpyxl,我如何找出.xlsx中合並了多少個單元格

[英]With openpyxl how can I find out how many cells are merged in .xlsx

我有工作表,其中“標題”在合並的單元格中,值在“標題”下的單元格中,請參見示例。

我如何計算標題跨越多少個單元格? 我需要知道在哪里開始和停止讀取屬於“標題”的單元格。

+-----------+-----------+
|  Heading1 | Heading2  |
+-----------+-----------+
| 1 | 2 | 3 | 3 | 3 | 4 |
+---+---+---+---+---+---+
| 4 | 5 | 6 | 3 | 3 | 3 |
+---+---+---+---+---+---+

您可以在Excel中的VBA中使用一個函數,如下所示

Public Function COLUMNSINMERGED(r As Excel.Range)

If r.MergeCells Then
    COLUMNSINMERGED=r.MergeArea.Columns.Count
    Debug.Print r.MergeArea.Address, "Cols : " & r.MergeArea.Columns.Count, "Rows : " & r.MergeArea.Rows.Count
else
   COLUMNSINMERGED=r.cells.count      
End If

End Function

您可以將convertLetterToColumnNum函數從Excel列號轉換為文本

#calculates the span given a merged cell
#first checks to see if cell is merged and then calculates the span
def calculateSpan(sheet, cell):
    idx = cell.coordinate
    for range_ in sheet.merged_cell_ranges:
        merged_cells = list(openpyxl.utils.rows_from_range(range_))
        for row in merged_cells:
            if idx in row:
                # If this is a merged cell
                first_col=convertLetterToColumnNum(str(merged_cells[0][0][0]))
                second_col = convertLetterToColumnNum(str(merged_cells[0][1][0]))
                span=abs(second_col-first_col)+1 #remove +1 if you want to count from zero
                return span

#usage
print(calculateSpan(mysheet,mysheet['D11']))

其余的是我如何獲取合並單元格中存在的價值的修改版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM