2012-04-12 21 views
0

これはC#の私の最初のコンソールアプリケーションプロジェクトで、Excelシートの使用領域を2次元配列にインポートしようとしています。これはこれを行う最も効率的な方法ではないかもしれませんが、これはこれまでのコードです。Excelから2次元配列にデータをインポート

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

0

エラーがすべてと言うを使用することができると思います二次元アレイ。なぜあなたはそれをキャストしようとしていますか?配列の必要はありませんし、あなたは単一のセルを読んでいます。しかし、範囲に1つ以上のセルが含まれている場合、結果は実際には2次元配列になります。あなたはCreateArrayFromValueを自分で実装する必要が当然の

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

return result; 

次に、あなたがこのようなものが必要。

+0

最初に未知数の行と列をインポートしようとしています。プログラムでこのコードを複数回使用しますが、範囲は新しいアプリケーションごとに異なります。 – Snuge

+0

更新された回答を参照してください。 –

+0

私は実用的なソリューションを見つけましたが、投稿することはできません。 – Snuge