2017-10-13 100 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