日期:2014-05-17 浏览次数:20976 次
private void button1_Click(object sender, EventArgs e)//导入Button { //dataGridView1.Columns.Clear(); //for (int i = 0; i < 27; i++) // dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Excel文件"; ofd.FileName = ""; ofd.InitialDirectory = Environment.GetFolderPath(Environment .SpecialFolder .MyDocuments ); ofd.Filter = "Excel文件(*.xls)|*.xls"; ofd.ValidateNames = true; ofd.CheckFileExists = true; ofd.CheckPathExists = true; string strName = string.Empty; if (ofd.ShowDialog() == DialogResult.OK) { strName = ofd.FileName; } if (strName == "") { MessageBox.Show("没有选择Excel文件!无法进行数据导入"); return; } ExcelToDataGridView(strName ,this.dataGridView1); } public void ExcelToDataGridView(string filePath,DataGridView dgv) { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + filePath + ";Extended Properties ='Excel 8.0;HDR=YES;IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn ); conn.Open(); string strExcel = ""; OleDbDataAdapter myCommand = null; DataSet ds = null; strExcel = "select * from [sheet4$]"; myCommand = new OleDbDataAdapter(strExcel ,strConn ); ds = new DataSet(); //myCommand.Fill(ds,"[sheet4$]"); myCommand.Fill(ds, "table1"); DataTable tb = new DataTable(); foreach (DataGridViewColumn dgvc in dgv.Columns) { if (dgvc.Visible && dgvc.CellType != typeof(DataGridViewCheckBoxCell)) { DataColumn dc = new DataColumn(); dc.ColumnName = dgvc.DataPropertyName; tb.Columns.Add(dc); } } foreach (DataRow excelRow in ds.Tables[0].Rows) { int i = 0; DataRow dr = tb.NewRow(); foreach (DataColumn dc in tb.Columns) { dr[dc ]=excelRow [i]; i++; } tb.Rows.Add(dr ); } dgv.DataSource = tb; }