2017-10-13 101 views
0

我正在尋找一種將Excel工作表的某些元素導入列表的方法。我的目標是能夠對excel工作表的屬性(第一行)進行排序(單擊我想查看的屬性)並獲取第一行下面的行的值。導入Excel行,列成列表

+1

您是否添加了excel作爲參考? – BugFinder

+1

可能的重複[我得到「缺少一個使用指令或程序集引用」,並沒有線索發生了什麼問題](https://stackoverflow.com/questions/17344295/im-getting-the-missing-a-using -directive-or-assembly-reference-and-no-clue-wh) – SeM

+0

你不需要寫'Excel.Sheets'。你已經使用了指令'Excel',所以只需要寫一個接口的'Sheet'即可。否則,您可以使用具體的類「工作表」。 – praty

回答

0

我會實現你想要的這種方式,而不使用Sheet接口,但Worksheet類對象。

有一點需要注意的是,在我獲得二維數組中所有使用的範圍之後,我正在關閉Excel表格。這使得速度更快,否則從範圍讀取會慢很多。可能有很多方法可以讓它更快。

Application xlApp = new Application(); 
Workbook xlWorkBook = null; 
Worksheet dataSheet = null; 
Range dataRange = null; 
List<string> columnNames = new List<string>(); 
object[,] valueArray; 

try 
{ 
    // Open the excel file 
    xlWorkBook = xlApp.Workbooks.Open(fileFullPath, 0, true); 

    if (xlWorkBook.Worksheets != null 
     && xlWorkBook.Worksheets.Count > 0) 
    { 
     // Get the first data sheet 
     dataSheet = xlWorkBook.Worksheets[1]; 

     // Get range of data in the worksheet 
     dataRange = dataSheet.UsedRange; 

     // Read all data from data range in the worksheet 
     valueArray = (object[,])dataRange.get_Value(XlRangeValueDataType.xlRangeValueDefault); 

     if (xlWorkBook != null) 
     { 
      // Close the workbook after job is done 
      xlWorkBook.Close(); 
      xlApp.Quit(); 
     } 

     for (int colIndex = 0; colIndex < valueArray.GetLength(1); colIndex++) 
     { 
      if (valueArray[0, colIndex] != null 
       && !string.IsNullOrEmpty(valueArray[0, colIndex].ToString())) 
      { 
       // Get name of all columns in the first sheet 
       columnNames.Add(valueArray[0, colIndex].ToString()); 
      } 
     } 
    } 

    // Now you have column names or to say first row values in this: 
    // columnNames - list of strings 
} 
catch (System.Exception generalException) 
{ 
    if (xlWorkBook != null) 
    { 
     // Close the workbook after job is done 
     xlWorkBook.Close(); 
     xlApp.Quit(); 
    } 
} 
+0

那個真的很好。短而且匹配的解決方案:) Thx再次爲您提供幫助! – Niclas

+0

所以我今天試了你的代碼。當程序進入catch(){}之前的最後一個if(){}時,我得到一個Exception。我沒有得到這個問題。我認爲這與情況有關。 – Niclas

+0

什麼是例外信息@Niclas?那可能是因爲'valueArray'是空的?在調試時在'valueArray'中看到了什麼? – praty