Tuesday, December 16, 2008

SpreadsheetML - Convert column integer index to column alpha value(i.e. A, AA, BH)

Here's a quick snippet I found in a forum post at http://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa. Many times in Excel I want to use a column index value instead of the letter representation(i.e A, AA, BH). I don't have control of the Excel so I can't change the representation. This method returns the letter representation from an integer column value.



protected string GetExcelColumnName(int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;

while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}

return columnName;
}

SpreadsheetML - Retrieving SharedString values

Retrieving cell values in Excel spreadsheets is very straight forward, especially when string values are stored inline. Other times the string values are stored in the SharedStringTable collection. If the CellType is a SharedString. then the cell value references the index in the SharedStringTable. Below is a quick snippet that will return the SharedString value if that is the case, otherwise the inline string value.

protected string GetCellValue(WorkbookPart wbPart, string targetCell)
{
string result = null;
WorksheetPart wsPart = wbPart.WorksheetParts.First();
SheetData sheetData = wsPart.Worksheet.GetFirstChild();
SharedStringTablePart sstPart = wbPart.GetPartsOfType().First();
SharedStringTable ssTable = sstPart.SharedStringTable;

try
{
Cell cell = wsPart.Worksheet.Descendants()
.Where(c => targetCell.Equals(c.CellReference))
.First();

if (cell.DataType != null && cell.DataType == CellValues.SharedString)
{
result = ssTable.ChildElements[Convert.ToInt32(cell.CellValue.Text)].InnerText;
}
else
{
if (cell.CellValue != null)
{
result = cell.CellValue.Text;
}
}
}
catch (Exception)
{

}

return result;
}