2016-04-09 11 views
0

このプログラムは、Excelファイルを2次元配列に読み込みます。今私は、元のExcelファイルと同じようなビューのようなグリッドで結果を表示する必要があります。私はDataGridViewが助けることができるかもしれないと言われました。続行する方法がわからないVB.netを使用すると、2次元配列の内容をフォームに表示するためにDataGridViewを実装する方法はありますか?

Imports Microsoft.Office.Interop.Excel 

Public Class Form1 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

新しいアプリケーションを作成します。

Dim excel As Application = New Application 

Excelスプレッドシートを開きます。

Dim w As Workbook = excel.Workbooks.Open("G:\PACE\New Style Project\01.xls") 

ループオーバー全シート。

For i As Integer = 1 To w.Sheets.Count 

シートを取得します。

 Dim sheet As Worksheet = w.Sheets(i) 

取得範囲。

 Dim r As Range = sheet.UsedRange 

Load all cells into 2d array. 
     Dim array(,) As Object = r.Value(XlRangeValueDataType.xlRangeValueDefault) 

セルをスキャンします。

 If array IsNot Nothing Then 
      'Console.WriteLine("Length: {0}", Array.Length) 

配列の境界を取得します。

  Dim bound0 As Integer = Array.GetUpperBound(0) 
      Dim bound1 As Integer = Array.GetUpperBound(1) 

      'Console.WriteLine("Dimension 0: {0}", bound0) 
      'Console.WriteLine("Dimension 1: {0}", bound1) 

すべての要素をループします。

  For j As Integer = 1 To bound0 
       For x As Integer = 1 To bound1 
        Dim s1 As String = Array(j, x) 
        'Console.Write(s1) 
        'Console.Write(" "c) 


       Next 
       'Console.WriteLine() 

      Next 
     End If 
    Next 

    ' Close. 
    w.Close() 
End Sub 

エンドクラス

+0

私たちはあなたの問題が解決されていることを願っています。そうでない場合は、あなたの質問を更新することを考えるかもしれません.... http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235 – Monty

答えて

1

これを達成するために迅速かつ簡単な方法はMicrosoft.ACE.OLEDB.12.0を使用することです.....ここ

は単純な例です....

Dim DataSet As New DataSet 
    Try 
     Dim con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "<Path to your Excel file>" + ";Extended Properties=Excel 12.0;") 

     con.Open() 
     Dim atatable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) 

     Dim sql As String 

     Dim excelcomm = New OleDbCommand() 
     Dim adexcel = New OleDbDataAdapter(excelcomm) 

     Dim tableInfo = con.GetSchema("Tables") 
     For Each row As DataRow In tableInfo.Rows 
      Console.WriteLine("{0}", row("TABLE_NAME").ToString) 
      Dim sheetname = row("TABLE_NAME").ToString 

      sql = "select * from [" + sheetname + "]" 
      adexcel.SelectCommand = New OleDbCommand(sql, con) 
      adexcel.Fill(DataSet, sheetname) 
     Next 


    Catch ex As Exception 

    End Try 
    DataGridView1.DataSource = DataSet.Tables(0) ' set DataGridView1 to display first table 

エラー

the 'microsoft.ace.oledb.12.0' provider is not registered on the local machine 
を取得する場合、最初のコードを試してみてくださいここから「con.Open()」を使用すると、AccessDatabaseEngine.exe(32ビット版ではない64ビット版)をインストールする必要があるかもしれませんで

https://www.microsoft.com/en-us/download/details.aspx?id=13255

関連する問題