。
/// < summary> /// 根据excel的文件的路径提取其中sheet表名称 /// /// < /summary> /// /// < param name="Path">Excel文件的路径< /param> private void GetDataFromExcelWithAppointSheetName(string Path) { try { //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;"; //备注: "HDR=yes;"是说Excel文件的第一行是列名而不是数据,"HDR=No;"正好与前面的相反。 //"IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。 //此连接可以操作.xls与.xlsx文件 (支持Excel2003 和 Excel2007 的连接字符串) strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties=‘Excel 12.0; HDR=Yes; IMEX=1‘"; conn = new OleDbConnection(strConn); conn.Open(); //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等 DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //包含excel中表名的字符串数组 string[] strTableNames = new string[dtSheetName.Rows.Count]; for (int k = 0; k < dtSheetName.Rows.Count; k++) { strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString(); } cmbSheets.DataSource = null; cmbSheets.Items.Clear(); cmbSheets.DataSource = strTableNames; if (strTableNames.Length == 0) { cmbSheets.DataSource = null; cmbSheets.Items.Add(" "); } } catch(Exception ex) { CommControl.MessageBoxEx.MessageBoxEx.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
private void btnRead_Click(object sender, EventArgs e) { if (strConn == "" || cmbSheets.Text.Trim()=="") return; OleDbDataAdapter myCommand = null; DataTable dt = new DataTable(); //从指定的表明查询数据,可先把所有表明列出来供用户选择 string strExcel = "select * from [" + cmbSheets.Text + "]"; myCommand = new OleDbDataAdapter(strExcel, strConn); dt = new DataTable(); myCommand.Fill(dt); //绑定到界面 dgvList.DataSource = dt; //LoadData(dt); tslState.Text = " 共" + dgvList.Rows.Count.ToString() + "条记录"; }
参见:
http://blog.csdn.net/hxy870/article/details/8618510
时间: 2024-10-12 12:19:28