【问题标题】:Get Index of last active columns per Row in Excel using Open XML使用 Open XML 在 Excel 中获取每行最后一个活动列的索引
【发布时间】:2015-06-24 17:50:23
【问题描述】:

如何使用 Open Xml 获取一行中最后一个活动列的索引

我在第 1 行有这个。

Dim activeCells As IEnumerable(Of DocumentFormat.OpenXml.Spreadsheet.Cell) =     row.Descendants(Of DocumentFormat.OpenXml.Spreadsheet.Cell)().Where(Function(c)      Not String.IsNullOrEmpty(c.InnerText))

Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = activeCells.LastOrDefault()
Dim CellRef As String = cell.CellReference

这给出了 D1",但我想要的是这种情况下的索引 "4"。我该怎么做?

【问题讨论】:

    标签: vb.net openxml


    【解决方案1】:

    要将单元格引用转换为列索引,您可以使用以下内容(我已将代码从 answer here 转换为您启发我编写的代码:))。

    Private Shared Function GetColumnIndex(cellReference As String) As System.Nullable(Of Integer)
        If String.IsNullOrEmpty(cellReference) Then
            Return Nothing
        End If
    
        'remove digits
        Dim columnReference As String = Regex.Replace(cellReference.ToUpper(), "[\d]", String.Empty)
    
        Dim columnNumber As Integer = -1
        Dim mulitplier As Integer = 1
    
        'working from the end of the letters take the ASCII code less 64 (so A = 1, B =2...etc)
        'then multiply that number by our multiplier (which starts at 1)
        'multiply our multiplier by 26 as there are 26 letters
        For Each c As Char In columnReference.ToCharArray().Reverse()
            columnNumber += mulitplier * (CInt(c) - 64)
    
            mulitplier = mulitplier * 26
        Next
    
        'the result is zero based so return columnnumber + 1 for a 1 based answer
        'this will match Excel's COLUMN function
        Return columnNumber + 1
    End Function
    

    注意:VB 可能不是惯用的,因为我使用 Telerik Converter 将其从 C# 转换为 VB。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-10
      • 2021-07-18
      • 2014-10-11
      • 1970-01-01
      • 2016-07-09
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多