2016-05-23 32 views
0

我需要从excel文件中提取一行并将其存储在数组中。我写了下面的代码。但是这似乎不是一个好的代码,因为执行时间会随着列数的增加而急剧增加。有没有更好的方法?将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

+0

您可能会考虑在http://codereview.stackexchange.com/ –

+0

上发布此信息每行是否有testscenarioId?这些身份证是排序的吗? – rene

+0

是的,每行都必须具有TestScenarioID。实际上,ID本身将从其他Excel表格中提取出来并用于此功能。 (提取需要在一张纸上执行的场景ID,并从另一张纸上提取针对这些ID的数据) – oshirwani

回答

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; 
    } 
} 

如果值对column1或column2进行排序可以实现BinarySearch,但是如果数据未排序并且无法将排序结果保存在某处,则先排序它无用。