【问题标题】:How can I get the address of xlsx cell containing provided value?如何获取包含提供值的 xlsx 单元格的地址?
【发布时间】:2018-08-28 13:03:18
【问题描述】:

我在 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];           
            }

在这里,我想知道如何使用提供的数据找到单元格索引。我想看一个带有任何字符串或其他东西的例子。 谢谢你的帮助!

【问题讨论】:

  • 你用的是什么库?你有什么代码?
  • 请为您的问题提供Minimal, Complete, and Verifiable Example。我们愿意为您提供帮助,但您需要先向我们表明您已尝试编写解决方案。
  • @Amy 我刚刚编辑过
  • 我很好奇为什么与加载电子表格有关的问题中没有代码?你有加载电子表格的代码吗?
  • @Amy 刚刚编辑

标签: c# excelpackage


【解决方案1】:

我不太明白你想做什么,但这是一种在 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;
}

【讨论】:

  • 这正是我想做的。谢谢。
  • 不客气,如果您需要什么,请随时询问
猜你喜欢
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
相关资源
最近更新 更多