syain.xlsx ※ Microsoft Office の Excel がインストールされている必要はありません Microsoft.ACE.OLEDB.12.0 を使用して、OleDbConnection と OleDbCommand でデータベースとして処理します。テーブル名としては、シート名が使われますが、範囲指定して名前を定義しない限りは [シート名$] をテーブル名として使用します。( カギかっこは、Oracle で言うところのダブルクォートです ) ※ ここでは : select * from [sheet1$] Microsoft.ACE.OLEDB.12.0 がインストールされていない場合 Microsoft Access データベース エンジン 2010 再頒布可能コンポーネントをダウンロードしてインストールします。 ( 32ビット版と64ビット版があるので選択してダウンロードします / ※ システム要件に 『32 ビット版の Access データベース エンジンは、Windows XP Service Pack 3 でしか使用できません』とあります。Windows7 では既にインストールされていると思われます ) ▼ ダウンロードページの『インストール方法』より抜粋OLEDB を使用するアプリケーション開発者: ConnectionString プロパティのプロバイダー引数を "Microsoft.ACE.OLEDB.12.0" に設定します。 Microsoft Office Excel データに接続する場合は、Excel ファイル形式に基づいて OLEDB 接続文字列の適切な拡張プロパティを追加します ファイル形式 (拡張子) 拡張プロパティ --------------------------------------------------------------------------------------------- Excel 97-2003 ブック (.xls) "Excel 8.0" Excel 2007-2010 ブック (.xlsx) "Excel 12.0 Xml" Excel 2007-2010 マクロ有効ブック (.xlsm) "Excel 12.0 Macro" Excel 2007-2010 XML 以外のバイナリ ブック (.xlsb) "Excel 12.0"処理コード
using System; using System.Data; using System.Data.OleDb; using System.Diagnostics; using System.Windows.Forms; namespace ExcelDataGridView { public partial class FormExcelGridView : Form { private string path = null; public FormExcelGridView() { InitializeComponent(); } private void loadExcelButton_Click(object sender, EventArgs e) { path = Helper.OpenFileDialog(); if (path == null) { return; } LoadExcel(); } // ********************* // Excel の読み込み // ********************* private void LoadExcel() { using (OleDbConnection myCon = new OleDbConnection()) using (OleDbCommand myCommand = new OleDbCommand()) { // SQL文字列格納用 string myQuery = "select * from [sheet1$]"; // 接続文字列の作成 myCon.ConnectionString = string.Format($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={path};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\""); Debug.WriteLine(myCon.ConnectionString); // ********************* // 接続 // ********************* try { // 接続文字列を使用して接続 myCon.Open(); // コマンドオブジェクトに接続をセット myCommand.Connection = myCon; // コマンドを通常 SQL用に変更 myCommand.CommandType = System.Data.CommandType.Text; } catch (Exception ex) { MessageBox.Show(this, ex.Message); return; } // ********************* // 実行 SQL // ********************* myCommand.CommandText = myQuery; // ********************* // レコードセット取得 // ********************* try { using (OleDbDataReader myReader = myCommand.ExecuteReader()) { DataTable dataTable = new DataTable(); dataTable.Load(myReader); dataGridView.DataSource = dataTable; // リーダを使い終わったので閉じる myReader.Close(); } } catch (Exception ex) { myCon.Close(); MessageBox.Show(this, ex.Message); return; } // 接続解除 myCon.Close(); } // 最外の using の終わり // カラム幅の自動調整 dataGridView.AutoResizeColumns(); } } }
Helpre クラス
class Helper { // https://msdn.microsoft.com/ja-jp/vba/excel-vba/articles/application-object-excel public const int xlMaximized = -4137; public const int xlMinimized = -4140; public const int xlNormal = -4143; public static string OpenFileDialog() { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Excel(*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|すべてのファイル(*.*)|*.*"; ofd.FilterIndex = 1; ofd.Title = "Excel ブックを選択してください"; ofd.RestoreDirectory = true; if (ofd.ShowDialog() != DialogResult.OK) { return null; } return ofd.FileName; } }
DataGridView のプロパティ
// // dataGridView // this.dataGridView.AllowUserToAddRows = false; this.dataGridView.AllowUserToDeleteRows = false; this.dataGridView.AllowUserToOrderColumns = true; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.Location = new System.Drawing.Point(12, 67); this.dataGridView.MultiSelect = false; this.dataGridView.Name = "dataGridView"; this.dataGridView.ReadOnly = true; this.dataGridView.RowTemplate.Height = 21; this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView.Size = new System.Drawing.Size(776, 371); this.dataGridView.TabIndex = 1;
関連する記事 C# : dynamic 型 による Excel へのアクセス このページの PDF