读取 EXCEL的工作表名,读取选中后工作表的列名
本文地址:http://www.cnblogs.com/vnii/archive/2011/09/02/2163381.html
读取Excel中所有工作表名
//是否已有字段头 string strHead = "YES"; if(chkHead.Checked==false) { strHead = "NO"; } string excelFilepath = openFileExcel.FileName; string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilepath + ";Extended Properties=\"Excel 12.0;HDR=" + strHead + ";\""; if ((System.IO.Path.GetExtension(excelFilepath)).ToLower() == ".xls") { strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilepath + ";Extended Properties=\"Excel 8.0;HDR=" + strHead + ";IMEX=1\""; } using (OleDbConnection conn = new OleDbConnection(strCon)) { conn.Open(); //返回在目录中定义的表 System.Data.DataTable schemeTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); for (int i = 0; i < schemeTable.Rows.Count; i++) { //工作表名 schemeTable.Rows[i][2].ToString().Trim() cmbSheets.Items.Add(schemeTable.Rows[i][2].ToString().Trim()); } if (cmbSheets.Items.Count > 0) { cmbSheets.Enabled = true; //cmbSheets.SelectedIndex = 0; } else { cmbSheets.Enabled = false; } }
读取工作表中的字段列名
//是否已有字段头 string strHead = "YES"; if (!bHead) { strHead = "NO"; } string strSheetName = ""; if(comboBoxSheets.SelectedIndex!=-1) { strSheetName = comboBoxSheets.SelectedItem.ToString(); } else { MessageBox.Show("选择工作表"); return; } string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFilepath + ";Extended Properties=\"Excel 12.0;HDR=" + strHead + ";\""; if ((System.IO.Path.GetExtension(strExcelFilepath)).ToLower() == ".xls") { strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelFilepath + ";Extended Properties=\"Excel 8.0;HDR=" + strHead + ";IMEX=1\""; } using (OleDbConnection conn = new OleDbConnection(strCon)) { //读取选择的工作表 OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter("Select * from [" + strSheetName + "]", conn); DataSet dataSet = new DataSet(); oleDbDataAdapter.Fill(dataSet, "mytb"); dataGridView.DataSource = dataSet.Tables["mytb"]; //工作表内容的列名,注意Excel连接串中的HDR属性 for (int i = 0; i < dataSet.Tables["mytb"].Columns.Count; i++) { comboBoxColumns.Items.Add(dataSet.Tables["mytb"].Columns[i].ColumnName); } comboBoxColumns.Enabled = true; }
参考网页:http://www.cnblogs.com/MR_ke/archive/2010/03/02/1676210.html
http://www.cnblogs.com/litianfei/archive/2008/03/21/1116906.html
http://hi.baidu.com/sunsung111/blog/item/685c5ae606831525b838206a.html