我在c#和xlsx文件中有一个准备好的字典,具有填充的列。如果单元格包含字典提供的值,则需要查找列索引和行索引。
我正在使用ExcelPackage和ExcelWorksheet。 字典:
public static Dictionary<string, string> ExcelColumnsMapping = new Dictionary<string, string>()
{
{"property name", "column name"}
}
XLS
var excelFile = new FileInfo(importFileFullPath);
using (ExcelPackage package = new ExcelPackage(excelFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
}
在这里,我想知道如何找到包含所提供数据的单元格索引。我想看看带有任何字符串或其他内容的示例。 谢谢您的帮助!
答案 0 :(得分:0)
我不知道您想做什么,但这是一种在xlsx文件中搜索值并返回找到的行和列的方法。
using Excel = Microsoft.Office.Interop.Excel; //you should add the reference to that library for it to work
public Tuple<int, int> search(string Providedvalue)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
int rCnt;
int cCnt;
int rw = 0;
int cl = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("path/exemple.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
rw = range.Rows.Count;
cl = range.Columns.Count;
bool found = false;
for (rCnt = 1; rCnt <= rw && found == false; rCnt++)
{
for (cCnt = 1; cCnt <= cl && found == false; cCnt++)
{
dynamic x = (range.Cells[rCnt, cCnt] as Excel.Range).Value2;
str = x.ToString();
if (Providedvalue == str)
{
int line = rCnt;
int column = cCnt;
return new Tuple<int, int>(line, column);
}
}
}
return null;
}