/// <summary> /// 读取Excel表格数据方法三,返回数据集DataSet /// </summary> /// <param name="str">所要打开的文件地址</param> /// <returns></returns> private DataSet GetExcelDataSet1(string strExcelFilePath) { try { ///建立连接,读取表格中的数据 string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + strExcelFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";///建立连接,地址为str传递的地址 OleDbConnection myConn = new OleDbConnection(strCon); string strCom = " SELECT * FROM [Sheet1$A:Q]";///SQL操作语句,就是说:取得所有数据从Sheet1 myConn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn); DataSet myDataSet = new DataSet();///建立新的数据集myDataSet myCommand.Fill(myDataSet, "[Sheet1$]");///填充数据集 myConn.Close(); int columnNum = myDataSet.Tables[0].Columns.Count;///读取列数并赋值给columnNum int rowNum = myDataSet.Tables[0].Rows.Count;///读取行数并赋值给rowNum int resultRowNum = columnNum - 1; Console.WriteLine("列数"+columnNum.ToString()); Console.WriteLine("行数" + rowNum.ToString()); Console.WriteLine("有效记录数" + resultRowNum.ToString()); ///读取结果行数(实际上就是去掉第一列编号列的列数,我的程序中将结果显示横置了) return myDataSet; } catch (Exception ex) { MessageBox.Show("发生错误" + ex.Message); return null; } }
C# 从Excel表中导入数据函数到DataSet
最新推荐文章于 2024-02-06 09:33:54 发布