【发布时间】:2015-06-22 16:21:17
【问题描述】:
使用 Interop.Excel 我使用:
CInt(oExcel.ActiveSheet.Cells(1, oExcel.ActiveSheet.Columns.Count).End(Microsoft.Office.Interop.Excel.XlDirection.xlToLeft).Column())
获取第 1 行的活动列数。
但是如何在 openxml 中实现呢?
【问题讨论】:
使用 Interop.Excel 我使用:
CInt(oExcel.ActiveSheet.Cells(1, oExcel.ActiveSheet.Columns.Count).End(Microsoft.Office.Interop.Excel.XlDirection.xlToLeft).Column())
获取第 1 行的活动列数。
但是如何在 openxml 中实现呢?
【问题讨论】:
我对 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),因此如果您希望将列作为数字,您可能需要对其进行解析。该代码还假定单元格是按顺序排列的,尽管我不认为 OpenXML 模式要求这样做,但我很确定 Excel 可以确保这一点。如果这导致问题,可以通过迭代单元格并跟踪最大列来解决。
注意:VB 可能不是惯用的,因为我使用 Telerik Converter 将其从 C# 转换为 VB。
【讨论】: