日期:2014-05-18 浏览次数:21267 次
//导入excel2007 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(); } }
------解决方案--------------------
安装驱动之类的全是扯谈 只要LZ你安装了 office2007 就没问题
我很久以前搞的时候 也是叫我安装驱动 安装XX之类的
全是扯蛋 后来我安装office2007 就搞定了
而且LZ爆的错根本就不是什么驱动的问题