使用Interop.Excel我使用:
CInt(oExcel.ActiveSheet.Cells(1, oExcel.ActiveSheet.Columns.Count).End(Microsoft.Office.Interop.Excel.XlDirection.xlToLeft).Column())
获取第1行的活动列数。
但是如何在openxml中实现呢?
答案 0 :(得分:0)
我对Interop.Excel不是很熟悉,但是代码看起来像是你正在获取 last 活动单元而不是表单中活动单元格的数量(尽管我可能会离开标记)。
我认为您可以使用OpenXML实现这样的目标:
Public Shared Sub GetActiveColumns(filename As String, rowNumber As Integer)
'open the document in read-only mode
Using spreadsheetDocument__1 As SpreadsheetDocument = SpreadsheetDocument.Open(filename, False)
'get the workbookpart
Dim workbookPart As WorkbookPart = spreadsheetDocument__1.WorkbookPart
'get the correct sheet from the workbookview
Dim workbookView As WorkbookView = workbookPart.Workbook.Descendants(Of WorkbookView)().First()
Dim index As Integer = If(workbookView.ActiveTab IsNot Nothing AndAlso workbookView.ActiveTab.HasValue, CInt(workbookView.ActiveTab.Value), 0)
Dim sheet As Sheet = workbookPart.Workbook.Descendants(Of Sheet)().ElementAt(index)
If sheet IsNot Nothing Then
'get the corresponding worksheetpart
Dim worksheetPart As WorksheetPart = TryCast(workbookPart.GetPartById(sheet.Id), WorksheetPart)
'get the row
Dim row As Row = worksheetPart.Worksheet.Descendants(Of Row)().Where(Function(r) r.RowIndex = rowNumber).FirstOrDefault()
'get the last cell
Dim activeCells As IEnumerable(Of Cell) = row.Descendants(Of Cell)().Where(Function(c) Not String.IsNullOrEmpty(c.InnerText))
Dim cell As Cell = activeCells.LastOrDefault()
Console.WriteLine("The last cell is {0} ", cell.CellReference)
Console.WriteLine("There are {0} cells with data in them", activeCells.Count())
End If
End Using
End Sub
给出以下表格
以上代码的输出是在1
传递rowNumber
时:
最后一个单元格是F1
有4个单元格中包含数据
CellReference
是您在公式中使用的引用(例如A1
),因此如果您希望将列作为数字,则可能需要解析该引用。该代码还假设单元格是按顺序排列的,我确信Excel确保尽管我不认为OpenXML模式要求它。如果这导致问题,可以通过迭代单元格并跟踪最大列来修复它。
注意:VB可能不是惯用的,因为我使用Telerik Converter将它从C#转换为VB。