将Excel工作表行提取到数组

时间:2016-05-23 15:50:24

标签: c# epplus

我需要从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

1 个答案:

答案 0 :(得分:0)

你可以做的事情不多,除非你找到你的行时提前纾困,并且可能会阻止在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;
    }
}

如果列1或列2中的值已排序,则实现BinarySearch,但如果数据未排序,并且您无法将排序结果保存在某处,则首先对其进行排序是无用的。 / p>