使用openpyxl,我如何找出.xlsx中合并了多少个单元格

时间:2016-07-13 07:37:38

标签: python excel openpyxl

我的表格中有"标题"在合并的单元格中,值在"标题"下的单元格中,参见示例。

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

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

2 个答案:

答案 0 :(得分:-1)

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

答案 1 :(得分:-1)

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

的修改版本