本文介绍了如何使用基于C#中每一行中的列的开放XML SDK读取xslx?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用打开的xml sdk读取一些.xslx文件,但是我真的在努力寻找任何好的示例.

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

我要做的是读取整个XSLX文件并循环浏览所有行,并从我指定的列中提取单元格值/单元格文本.

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.

类似以下内容:

GetCellText(rowId, ColumnLetter)

这可能吗?

推荐答案

助手:

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]+");

代码:

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

        }

这篇关于如何使用基于C#中每一行中的列的开放XML SDK读取xslx?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 09:29