在Excel文件中搜索字符串,并在C#中使用OpenXML返回搜索到的单元格的rowindex和columnindex

时间:2018-08-29 06:11:49

标签: c# openxml

我想在excel文件中搜索字符串,我曾经在程序中使用Microsoft.Office.Interop.Excel,并且运行良好。我在下面使用此代码:

 findRange1 = range1.Find("apple", LookAt: Excel.XlLookAt.xlWhole);

但是,我在服务器端使用interop excel时遇到了问题。然后我使用OpenXML更改程序。我也想使用OpenXML进行搜索。如何在OpenXML中做到这一点?

1 个答案:

答案 0 :(得分:0)

1)将您的Excel文档.xlsxxls导入到SpreadsheetDocument的{​​{1}}中。

OpenXMl

2)使用特定的搜索条件创建以public WorkbookPart ImportExcel() { try { string path = @"your path to excel document"; using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { MemoryStream m_ms = new MemoryStream(); fs.CopyTo(m_ms); SpreadsheetDocument m_Doc = SpreadsheetDocument.Open(m_ms, false); return m_Doc.WorkbookPart; } } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.Message + ex.StackTrace); } return null; } 形式获取索引的方法。

[row, column]

3)最后,此方法通过传递列名来为您提供列索引。

public string GetIndexBySearch(string search)
        {

            WorkbookPart workbookPart = ImportExcel();
            var sheets = workbookPart.Workbook.Descendants<Sheet>();
            Sheet sheet = sheets.Where(x => x.Name.Value == "you sheet name in excel document").FirstOrDefault();

            string index = string.Empty;

            if (sheet != null)
            {
                var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                var rows = worksheetPart.Worksheet.Descendants<Row>().ToList();

                // Remove the header row
                rows.RemoveAt(0);

                foreach (var row in rows)
                {
                    var cellss = row.Elements<Cell>().ToList();

                    foreach (var cell in cellss)
                    {
                        var value = cell.InnerText;
                        var stringTable = workbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                        value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                        bool isFound = value.Trim().ToLower().Contains(search.Trim().ToLower());

                        if (isFound)
                        {
                            index = $"[{row.RowIndex}, {GetColumnIndex(cell.CellReference)}]";
                            return index;
                        }

                    }
                }
            }

            return index;
        }

4)考虑到以上三种方法都在称为private static int? GetColumnIndex(string cellReference) { if (string.IsNullOrEmpty(cellReference)) { return null; } 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; } 的同一类中。然后,您将像使用MyClass

GetIndexBySearch

输出:

enter image description here