2016-05-23 103 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,但是如果數據未排序並且無法將排序結果保存在某處,則先排序它無用。