user1828871
user1828871

Reputation: 191

How to read xslx with open XML SDK based on columns in each row in C#?

I am trying to read some .xslx files with the open xml sdk, but I'm really struggeling finding any good examples.

What I want to do is to read the entire XSLX file and loop through all of the rows and extract the cellvalue/celltext from the columns i specify.

Like the following:

GetCellText(rowId, ColumnLetter)

Is this possible?

Upvotes: 2

Views: 11251

Answers (2)

Encarmine
Encarmine

Reputation: 453

Helpers:

private static string GetColumnName(string cellReference)
{
    if (ColumnNameRegex.IsMatch(cellReference))
        return ColumnNameRegex.Match(cellReference).Value;

    throw new ArgumentOutOfRangeException(cellReference);
}

private static readonly Regex ColumnNameRegex = new Regex("[A-Za-z]+");

Code:

using (var document = SpreadsheetDocument.Open(stream, true))
        {
            var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();

            foreach (Sheet sheet in sheets)
            {

                WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
                Worksheet worksheet = worksheetPart.Worksheet;
                var rows = worksheet.GetFirstChild<SheetData>().Elements<Row>();
                foreach (var row in rows)
                {
                    var cells = row.Elements<Cell>();
                    foreach (var cell in cells)
                    {
                        if(GetColumnName(cell.CellReference) == "A")
                        {
                            var str = cell.CellValue.Text;
                            // do whatewer you want
                        }
                    }
                }
            }

        }

Upvotes: 3

Akanksha Gaur
Akanksha Gaur

Reputation: 2686

Your question is similar to this one

1) Open xml excel read cell value

You can get the row by ID and look-up the value by column name.

Hope that helps

Upvotes: 0

Related Questions