private bool ReadSheetDimensions() { while (reader.Read()) { if (reader.ElementType == typeof(DocumentFormat.OpenXml.Spreadsheet.SheetDimension)) { // Read sheet dimensions DocumentFormat.OpenXml.OpenXmlAttribute attribute = reader.Attributes .First(a => a.LocalName == "ref"); string[] words = attribute.Value.Split(new char[] { ':' }); if (words.Length < 2) { columnCount = 0; rowCount = 0; return(true); } columnCount = ColumnNameToIndex(GetColumnNameFromCellReference(words[1])); rowCount = Convert.ToInt32(GetRowNameFromCellReference(words[1])); /* * int fromColumn = ColumnNameToIndex(GetColumnNameFromCellReference(words[0])); * int toColumn = ColumnNameToIndex(GetColumnNameFromCellReference(words[1])); * * this.columnCount = toColumn - fromColumn + 1; * * int fromRow = Convert.ToInt32(GetRowNameFromCellReference(words[0])); * int toRow = Convert.ToInt32(GetRowNameFromCellReference(words[1])); * * this.rowCount = toRow - fromRow + 1; */ return(true); } if (reader.ElementType == typeof(DocumentFormat.OpenXml.Spreadsheet.SheetData)) { // Sheet data reached, stop searching for sheet dimensions return(true); } } return(false); }
/// <summary> /// Moves to the next row of current worksheet. /// </summary> /// <returns>True if success.</returns> public bool MoveToNextRow(bool allowEmptyRow = false) { currentCellPosition = 1; if (currentRowPosition < currentRowIndex) { // This row does not exist in worksheet (the row is empty) currentRowPosition++; return(true); } Type rowType = typeof(DocumentFormat.OpenXml.Spreadsheet.Row); Type cellType = typeof(DocumentFormat.OpenXml.Spreadsheet.Cell); while (reader.Read()) { if (reader.IsStartElement && (reader.ElementType == rowType)) { // Read next available row DocumentFormat.OpenXml.OpenXmlAttribute attribute = reader.Attributes .First(a => a.LocalName == "r"); currentRowIndex = Convert.ToInt32(attribute.Value); // Fix: for first row with zero index (invalid) if (currentRowIndex == 0) { currentRowIndex = 1; } currentRowPosition++; currentCell = null; currentCellIndex = 0; currentCellPosition = 0; if (reader.ReadFirstChild()) { // Row contains cells if (reader.IsStartElement && (reader.ElementType == cellType)) { // Read first available cell currentCell = (DocumentFormat.OpenXml.Spreadsheet.Cell)reader.LoadCurrentElement(); currentCellIndex = ColumnNameToIndex(GetColumnNameFromCellReference(currentCell.CellReference)); currentCellPosition = 1; // Move to the next cell reader.ReadNextSibling(); return(true); } } else { // Row is empty return(allowEmptyRow); } } } return(false); }