DataGridView、一個 TextBox、兩個 Button。Sheet1 第一行設定欄位名。Resources.resx,將 Excel 檔案加入資源(名為 Excel)。string excelPath = AppDomain.CurrentDomain.BaseDirectory + "Excel" + DateTime.Now.Ticks + ".xlsx";
if (System.IO.File.Exists(excelPath)) { /* 已存在處理 */ return; }
try {
System.IO.FileStream fs = new System.IO.FileStream(excelPath, FileMode.OpenOrCreate);
fs.SetLength(0);
fs.Write(Properties.Resources.Excel, 0, Properties.Resources.Excel.Length);
fs.Close(); fs.Dispose();
textBox1.Text = "提取 Excel 檔案成功!\r\n";
}
catch (Exception ex) { /* 錯誤處理 */ }
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;Persist Security Info=False;" + "data source=" + @excelPath + ";Extended Properties='Excel 12.0; HDR=yes; IMEX=10'"; // 注意:IMEX=10 而非 1 或 2,避免「可更新查詢」錯誤
DataTable oleDt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); dataGridView1.DataSource = oleDt;
OleDbCommand cmd = new OleDbCommand("Insert Into [Sheet1$] Values('abc', 'bac', '0', '123456', 'test','測試','aa')", conn);
cmd.ExecuteNonQuery(); // 重複執行插入多筆
注意:存取 Excel 工作表需在名稱後加 $ 符號(如 [Sheet1$])。
cmd = new OleDbCommand("Select * From [Sheet1$]", conn);
OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
dataGridView2.DataSource = ds.Tables[0];
DataTable dt = conn.GetSchema(); /* 列印欄位名與資料 */
if (conn.State != ConnectionState.Closed) conn.Close();
System.Diagnostics.Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory);