有了openpyxl,我怎样才能知道在.xlsx中合并了多少个单元格

2024-04-27 14:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张表,其中“heading”在合并单元格中,值在“heading”下的单元格中,见示例。在

如何计算标题跨越多少个单元格?我需要知道从哪里开始和停止读取属于“标题”的单元格。在

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

Tags: 标题示例headingheading2heading1
2条回答

您可以在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

您可以从Excel Column Number to Text获得convertLetterToColumnNum函数

#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']))

其余的是How do i get value present in a merged cell的修改版本

相关问题 更多 >