【问题标题】:Extract an excel sheet row to an array将excel工作表行提取到数组
【发布时间】:2016-05-23 15:50:23
【问题描述】:

我需要从 excel 文件中提取一行并将其存储在一个数组中。我已经编写了以下代码。但这似乎不是一个好的代码,因为随着列数的增加,执行时间会急剧增加。有没有更好的办法?

public static System.Array eEPlueExtractOneRowDataAgainstTSAndTCIDFromAnExcelSheet(string fullExcelFilePath, string excelSheetName, string testScenarioId, string testCaseId)
    {
        //Define variables
        System.Array myArray = null;

        //Define the excel file
        FileInfo desiredExcelFile = new FileInfo(fullExcelFilePath);


        //Manipulate Excel file using EPPlus
        ExcelPackage excelPkg = new ExcelPackage(desiredExcelFile);
        ExcelWorksheet workSheet = excelPkg.Workbook.Worksheets[excelSheetName];
        int totalRows = workSheet.Dimension.End.Row;
        int totalColums = workSheet.Dimension.End.Column;
        Console.WriteLine("Total Rows & Colums - " + totalRows + ":" + totalColums);
        Console.WriteLine("");


        for (int i = 1; i <= totalRows; i++)
        {
            if ( (workSheet.Cells[i, 1].Value.ToString() == testScenarioId) && (workSheet.Cells[i, 2].Value.ToString() == testCaseId) )
            {
                //Console.Write("Desired Row is: " + i);
                myArray = new string[totalColums];
                for (int j = 1; j < totalColums; j++)
                {
                    myArray.SetValue(workSheet.Cells[i, j].Value.ToString(), (j - 1));
                }
            }
        }


        return myArray;
    }

我不想使用 Microsoft.Office.Interop.Excel。我必须使用 EPPlus

【问题讨论】:

  • 你可以考虑在codereview.stackexchange.com上发帖
  • 每一行都有一个testscenarioId吗?那些 id 排序了吗?
  • 是的,每一行都必须有 TestScenarioID。实际上,ID 本身将从其他一些 Excel 工作表中提取,并将在此函数中使用。 (从一张表中提取需要执行的scenarioId,并从另一张表中针对这些ID提取数据)
  • 参考这个链接github.com/pruiz/EPPlus/blob/master/SampleApp/Sample8.cs你应该有更好的选择使用linq

标签: c# epplus


【解决方案1】:

您无能为力,除了在找到您的行时尽早退出,并可能防止在 if 语句中创建太多字符串:

for (int i = 1; i <= totalRows; i++)
{
    if (testScenarioId.Equals(workSheet.Cells[i, 1].Value) && 
        testCaseId.Equals(workSheet.Cells[i, 2].Value) )
    {
        //Console.Write("Desired Row is: " + i);
        myArray = new string[totalColums];
        for (int j = 1; j < totalColums; j++)
        {
            myArray.SetValue(workSheet.Cells[i, j].Value.ToString(), (j - 1));
        }
        // stop iterating the for loop
        break;
    }
}

如果 column1 或 column2 中的值已排序,则您实现 BinarySearch,但如果数据未排序并且您无法将排序结果存储在某处,则首先对其进行排序是无用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2013-09-26
    • 1970-01-01
    相关资源
    最近更新 更多