最近做項目,遇到了處理Excel的問題,要求以Excel為數據源,直接將Excel的數據在dataGridView中顯示,主要是分三步進行。
第一:創建Excel文件的連接;
第二:將Excel數據放入datatable;
第三:綁定數據。
//創建Excel文件的連接,返回連接字符串
private string GetStr()
{
string connectionString = string.Empty;
OpenFileDialog f = new OpenFileDialog();
f.ShowDialog();
if (f.FileName != "")
{
if (lookUpEdit1.EditValue.ToString() == "2003")//Excel版本不一樣,連接字符串也是不一樣的
{
//Excel2003
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + f.FileName + ";" + "Extended Properties=Excel 8.0 ;"
}
else
{
//excel2007、2010
connectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=NO;IMEX=1""", f.FileName);
}
}
return connectionString;
}
private void Btn_導入_Click(object sender, EventArgs e)
{
if (gridResult == null) return;
// gridResult.Init(bga.db);
gridResult.CurrentDataSet.Tables[0].Clear();//清空數據
DataTable dt_result=gridResult.CurrentDataSet.Tables[0].Clone();
OleDbConnection conn = null;
DataTable dt = new DataTable();
string connectionString = string.Empty;
string filepath = GetStr();
string strSheetName = "";
if (filepath != "" || filepath.Length > 0)
{
try
{
conn = new OleDbConnection(filepath);
conn.Open();
System.Data.DataTable dtTemp = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); strSheetName = dtTemp.Rows[0][2].ToString().Trim();//獲取工作薄的name
OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + strSheetName + "]", conn); //根據工作薄的名字查找對應工作薄的數據
oada.Fill(dt);
conn.Close();
gridResult.DataSource = dt;
gridResult.Refresh();
gridResult.CurrentDataSet.Tables[0] = dt;
XControl.bga_grid.gridResult = null;
this.Dispose();//釋放資源
this.Close();
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message+" 請重新選擇Excel版本");
return;
}
}
}