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

若如初见. 提交于 2021-02-10 05:31:09

问题


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?


回答1:


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
                        }
                    }
                }
            }

        }



回答2:


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



来源:https://stackoverflow.com/questions/13412143/how-to-read-xslx-with-open-xml-sdk-based-on-columns-in-each-row-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!