Cell.CellReference возвращает null
Почему CellReference return null Как избежать?
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
foreach (Row r in sheetData.Elements<Row>())
{
DataRow rs = pt.ListImport.NewRow();
if (nrow > 0)
{
foreach (Cell c in r.Elements<Cell>())
{
if (c.CellReference == null)
continue;
string s = c.CellValue.InnerTex;
}
}
}
}
Ответы (1 шт):
Автор решения: Игорь Степенский
→ Ссылка
В моем случае это решило вопрос
foreach (Row r in sheetData.Elements<Row>())
{
if (r.RowIndex > 2)
{
int nc = 0;
foreach (Cell c in r.Elements<Cell>())
{
if (!string.IsNullOrEmpty(c.CellReference))
nc = GetNumByRef(c.CellReference);
else
nc++;
if (c.CellValue == null)
{
continue;
}
string s = c.CellValue.InnerTex
//...
}
}
private int GetNumByRef(string cellReference)
{
// функция из https://stackoverflow.com/questions/28875815/get-the-column-index-of-a-cell-in-excel-using-openxml-c-sharp
string columnReference = Regex.Replace(cellReference.ToUpper(), @"[\d]", string.Empty);
int columnNumber = -1;
int mulitplier = 1;
foreach (char c in columnReference.ToCharArray().Reverse())
{
columnNumber += mulitplier * ((int)c - 64);
mulitplier = mulitplier * 26;
}
return columnNumber + 1;
}