using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace FastExcel
{
///
/// Row that contains the Cells
///
public class Row
{
///
/// The Row Number (Row numbers start at 1)
///
public int RowNumber { get; set; }
///
/// The collection of cells for this row
///
public IEnumerable Cells { get; set; }
///
/// Create a new Row
///
/// Row number starting with 1
/// Cells on this row
public Row(int rowNumber, IEnumerable cells)
{
if (rowNumber <= 0)
{
throw new Exception("Row numbers starting at 1");
}
RowNumber = rowNumber;
Cells = cells;
}
///
/// Constructor
///
public Row(XElement rowElement, Worksheet worksheet)
{
try
{
RowNumber = (from a in rowElement.Attributes("r")
select int.Parse(a.Value)).First();
}
catch (Exception ex)
{
throw new Exception("Row Number not found", ex);
}
if (rowElement.HasElements)
{
Cells = GetCells(rowElement, worksheet);
}
}
///
/// Retreive cell that is in column specified
///
/// Column letter or defined name
/// Matching cell or null if not found
public Cell GetCellByColumnName(string columnName)
{
return (from c in Cells where c.ColumnName == columnName select c).FirstOrDefault();
}
//
// Get all cells in this row.
//
private IEnumerable GetCells(XElement rowElement, Worksheet worksheet)
{
foreach (XElement cellElement in rowElement.Elements())
{
yield return new Cell(cellElement, worksheet);
}
}
//
// Output Row as an Xml element with cells nested
//
internal StringBuilder ToXmlString(SharedStrings sharedStrings)
{
var row = new StringBuilder();
if (Cells != null && Cells.Any())
{
row.AppendFormat("", RowNumber);
try
{
foreach (Cell cell in Cells)
{
row.Append(cell.ToXmlString(sharedStrings, RowNumber));
}
}
finally
{
row.Append(" ");
}
}
return row;
}
///
/// Merge this row and the passed one togeather
///
/// Row to be merged into this one
internal void Merge(Row row)
{
// Merge cells
var outputList = new List();
foreach (var cell in Cells.Union(row.Cells).GroupBy(c => c.ColumnNumber))
{
int count = cell.Count();
if (count == 1)
{
outputList.Add(cell.First());
}
else
{
cell.First().Merge(cell.Skip(1).First());
outputList.Add(cell.First());
}
}
// Sort
Cells = (from c in outputList
orderby c.ColumnNumber
select c);
}
}
}
| | | |