2

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

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

4

1 回答 1

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

                        */

                    }
                }
            }           
        }
    }
}
于 2012-08-31T16:14:05.970 回答