在电子表格中搜索输入字符串

时间:2012-08-30 13:22:54

标签: excel openxml spreadsheet

我正在使用Open XML SDK打开Excel文件(xlsx),我想查找从外部传递的特定字符串或整数,以检查电子表格中值的重复项。

如何在电子表格的所有单元格中搜索输入字符串?

1 个答案:

答案 0 :(得分:3)

下面:

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();

                        */

                    }
                }
            }           
        }
    }
}