我正在使用Open XML SDK打開Excel文件(xlsx),我想要查找從外部傳遞的特定字符串或整數以檢查電子表格中值的重複項。搜索電子表格中的輸入字符串
如何在電子表格的所有單元格中搜索輸入字符串?
我正在使用Open XML SDK打開Excel文件(xlsx),我想要查找從外部傳遞的特定字符串或整數以檢查電子表格中值的重複項。搜索電子表格中的輸入字符串
如何在電子表格的所有單元格中搜索輸入字符串?
這裏:
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();
*/
}
}
}
}
}
}
感謝response.wud想知道如果在Excel中寫入的字符串不存在於SharedStringTable表中,會發生什麼情況。單元格值的數據類型是字符串類型不是共享字符串類型。那麼如何從中檢索單元格值擅長進行搜索。 –
解決方案有效 –
難道我的解決方案的工作? – jn1kk