Search of an input string in spreadsheet

﹥>﹥吖頭↗ 提交于 2019-12-08 07:46:57

问题


I am using the Open XML SDK to open an Excel file (xlsx) and I want to find a specific string or integer passed from outside to check for duplicates of the value in the spreadsheet.

How can I search for the input string in all the cells of spreadsheet?


回答1:


Here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(@"C:\Users\user\Desktop\Book1.xlsx", true))
            {
                Sheet sheet = document.WorkbookPart.Workbook.Descendants<Sheet>().First<Sheet>();
                Worksheet worksheet = ((WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id)).Worksheet;
                IEnumerable<Row> allRows = worksheet.GetFirstChild<SheetData>().Descendants<Row>();
                foreach (Row currentRow in allRows)
                {
                    IEnumerable<Cell> allCells = currentRow.Descendants<Cell>();
                    foreach (Cell currentCell in allCells)
                    {
                        CellValue currentCellValue = currentCell.GetFirstChild<CellValue>();
                        string data = null;
                        if (currentCell.DataType != null)
                        {
                            if (currentCell.DataType == CellValues.SharedString) // cell has a cell value that is a string, thus, stored else where
                            {
                                data = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault().SharedStringTable.ElementAt(int.Parse(currentCellValue.Text)).InnerText;
                            }
                        }
                        else
                        {
                            data = currentCellValue.Text;
                        }
                        Console.WriteLine(data);

                        /* 
                            your code here

                                if(data.contains("myText"))
                                    doSomething();

                        */

                    }
                }
            }           
        }
    }
}


来源:https://stackoverflow.com/questions/12197881/search-of-an-input-string-in-spreadsheet

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