日期:2014-05-18 浏览次数:21044 次
//导入excel2007到datagridview 如果LZ想同时导入多个的话 能实现 但是很烦 建议很少一个一个的导入 public void EcxelToDataGridView(string filePath, DataGridView dgv) { //根据路径打开一个excel文件并将数据填充到dataset中 string strConn = @"Provider = Microsoft.Ace.OLEDB.12.0; Data Source = " + filePath + "; Extended Properties = 'Excel 12.0;HDR = NO; IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); string strExcel = ""; strExcel = "select * from [sheet1$]"; DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); string tableName = schemaTable.Rows[0][2].ToString().Trim(); OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn); DataSet ds = new DataSet(); myCommand.Fill(ds, "table1"); //根据DataGridView的列构造一个DataTable DataTable td = ds.Tables[0]; try { //MessageBox.Show(td.ToString()); foreach (DataGridViewColumn dgvc in dgv.Columns) { if (dgvc.Visible && dgvc.CellType != typeof(DataGridViewCheckBoxCell)) { DataColumn dc = new DataColumn(); dc.ColumnName = dgvc.DataPropertyName; dc.DataType = dgvc.ValueType; //MessageBox.Show(dc.ToString()); td.Columns.Add(dc); } } //根据excel的行逐一对上面的构造的datatable的列进行赋值 for (int i = 0; i < ds.Tables[0].Rows.Count - 1; i++) { //int j = 0; DataRow dr = td.NewRow(); DataRow excelRow = ds.Tables[0].Rows[i]; foreach (DataColumn dc in td.Columns) { dr[dc] = excelRow[i]; //MessageBox.Show(dr[dc].ToString()); i++; } td.Rows.Add(dr); } //在datagridview中显示导入的数据 dgv.DataSource = td; } catch (Exception) { MessageBox.Show("该表已存在你即将导入的excel文件...,请点击清空按钮重新导入..."); return; } finally { conn.Close(); } }