【问题标题】:Include empty spaces when selecting from row in Open XML从 Open XML 中的行中选择时包含空格
【发布时间】:2023-04-06 16:03:01
【问题描述】:

我的 Excel 是这样的

 A    B    C    D
      1    2    3

我用这个,

Dim row As DocumentFormat.OpenXml.Spreadsheet.Row = sheetData.Descendants(Of DocumentFormat.OpenXml.Spreadsheet.Row)().FirstOrDefault(Function(y) y.RowIndex.Value = 1)

我的结果中只有 3 个单元格(B、C、D)。我如何包含空格?

【问题讨论】:

    标签: vb.net openxml


    【解决方案1】:

    Excel 文件仅包含填有其地址的单元格。空单元格是“虚拟的”。

    您可以通过地址单元格检查,“丢失”的单元格是 . 要将地址(“A1”样式)转换为数字索引,您可以使用此功能(信用:codeproject Article: Read and Write Microsoft Excel with Open XML SDK):

    dim regexColName = New Regex("[A-Za-z]+", RegexOptions.Compiled)
    
    Private Function ConvertCellReferenceToNumber(cellReference As String) As Integer
        Dim colLetters = regexColName.Match(cellReference).Value.ToCharArray()
        Array.Reverse(colLetters)
    
        Dim convertedValue = Asc(colLetters(0)) - 65
    
        For i = 1 To colLetters.Length - 1
            Dim current = Asc(colLetters(i)) - 64
            convertedValue += current * Math.Pow(26, i)
        Next
    
        Return convertedValue
    End Function
    

    使用此功能,您可以模拟空单元格:

    Dim row As Row = SheetData.Descendants(Of Row)().FirstOrDefault(Function(y) y.RowIndex.Value = 2)
    
    Dim cells = row.Descendants(Of Cell).ToDictionary(
        Function(cell) ConvertCellReferenceToNumber(cell.CellReference),
        function(cell) cell)
    
    For i = 0 To cells.Keys.Max()
        Dim c As Cell
        If (cells.TryGetValue(i, c)) Then
            Console.WriteLine(c.CellValue) 'need hanle for special values 
        Else
            Console.WriteLine("empty")
        End If
    Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2016-03-08
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多