2012-04-12 55 views
0

這是我在C#中的第一個控制檯應用程序項目,我試圖將Excel表的使用區域導入到二維數組中。這可能不是最有效的方法,但這是迄今爲止的代碼。將數據從excel導入二維數組

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using Excel = Microsoft.Office.Interop.Excel; 
using System.Reflection; 

Excel.Application excelApp = new Excel.Application(); 
     excelApp.Visible = true; 
     string workbookPath = "C:/Users/Snuge/Desktop/CourseNumbersNoWSReg.xlsx"; 
     Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 
       0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", 
       true, false, 0, true, false, false); 

     // This selectes the used range of the excel workbook and enters it in 
     // a two dimentional array 
     try 
     { 
      // Get a reference to the first sheet of the workbook. 
      Excel.Sheets excelSheets = excelWorkbook.Worksheets; 
      string currentSheet = "Sheet1"; 
      Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet); 

      // write out to console for debugging 
      Console.WriteLine("excelWorksheet is " + excelWorksheet); 

      // Get a range of data. 
      Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A3", Missing.Value); 

      // write out to console for debugging 
      Console.WriteLine("excelCell is " + excelCell); 

      // write out to console for debugging 
      Console.WriteLine("Creating string[,] array. . . "); 
      // Retrieve the data from the range. 
      Object[,] dataArray; 
      // write out to console for debugging 
      Console.WriteLine("String[,] array created. . . "); 

      dataArray = (System.Object[,])excelCell.get_Value(Missing.Value); 

      // write out to console for debugging 
      Console.WriteLine("Counting rows and columns. . . "); 
      // Determine the dimensions of the array. 
      int iRows; 
      int iCols; 
      iRows = dataArray.GetUpperBound(0); 
      iCols = dataArray.GetUpperBound(1); 

      // write out to console for debugging 
      Console.WriteLine("Printing array. . . "); 
      // Print the data of the array. 
      for (int rowCounter = 1; rowCounter <= iRows; rowCounter++) 
      { 
       // write out to console for debugging 
       Console.WriteLine("row " + rowCounter); 
       for (int colCounter = 1; colCounter <= iCols; colCounter++) 
       { 

        // Write the next value to the console. 
        Console.WriteLine("col " + colCounter + "= " + dataArray[rowCounter, colCounter].ToString() + ", "); 
       } 
       // Write in a new line. 
       Console.WriteLine("\n"); 
      }     
     } 

     catch (Exception theException) 
     { 
      // Create error message 
      String errorMessage; 
      errorMessage = "Error: "; 
      errorMessage = String.Concat(errorMessage, theException.Message); 
      errorMessage = String.Concat(errorMessage, " Line: "); 
      errorMessage = String.Concat(errorMessage, theException.Source); 
      // Display error message 
      MessageBox.Show(errorMessage, "Error"); 
     } 

我插入了Console.Writeline();用於調試目的。正確的Excel工作簿打開,我在命令提示符下獲得的輸出是

excelWorksheet is System.__ComObject 
excelCell is System.__ComObject 
Creating string[,] array. . . 
String[,] array created. . . 

然後一個消息框與消息

"Error: Cannot convert type 'string' to object[*,*] Line: Anonymously Hosted DynamicMethods Assembly".  

這行代碼給我一個錯誤彈出,我不不知道爲什麼。

dataArray = (System.Object[,])excelCell.get_Value(Missing.Value); 

有人能爲我提供解決這個問題的解決方案嗎?

另外,是否有代碼在命令提示符下顯示值而不是「System .__ ComObject」?

我使用的是Excel 2007,並添加了Microsoft Excel 12.0 Object Library參考。

回答

1

我想你可以使用

// This value "should" be boxed into two-dimensional array 
object dataArray = excelCell.Value; 

var dataArray = (object[,])excelCell.Value2; 
+0

Marco,'object dataArray = excelCell.Value;',我如何在這個上使用索引?如果我想獲得像[1,1]或[2,1]這樣的特定數據,是否有辦法將其索引? – Maddy 2017-07-06 13:15:30

0

錯誤說,所有的,它不能轉換成字符串類型的值(這是在一個單元中的數據很明顯),以兩輪二維數組。你爲什麼試圖這麼做?沒有必要陣列,然後你閱讀一個單元格。但是如果你的範圍包含多於一個單元格,那麼返回的結果確實是二維數組。

然後,你需要這樣的事:

object[,] result; 
object rawData = excelCell.get_Value(Missing.Value); 
if(rawData.GetType().IsArray()) 
{ 
    result = rawData; 
} 
else 
{ 
    result = CreateArrayFromValue(rawData); 
} 

return result; 
當然,你需要實現 CreateArrayFromValue自己的

+0

我正在嘗試導入最初未知的數字行和列。我將在我的程序中多次使用此代碼,但是每個新應用程序的範圍會有所不同。 – Snuge 2012-04-12 09:25:21

+0

查看更新的答案。 – 2012-04-12 09:44:59

+0

我發現了一個工作解決方案,但它不會讓我發佈它。 – Snuge 2012-04-12 12:36:06