//读取EXCEL public static DataSet LoadDataFromExcel(string filePath) //加载excel 返回DataSet内存数据库 { try { string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'"; OleDbConnection OleConn = new OleDbConnection(strConn); OleConn.Open(); String sql = "SELECT * FROM [Sheet1$]";//可是更改Sheet名称,比如sheet2,等等 OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn); DataSet OleDsExcle = new DataSet(); OleDaExcel.Fill(OleDsExcle, "Sheet1"); OleConn.Close(); return OleDsExcle; } catch (Exception err) { MessageBox.Show("数据绑定Excel失败!失败原因:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return null; } }
//读取private void button1_Click(object sender, EventArgs e) { string excelPath = "测试.xlsx"; //文件路径 string fileExt = Path.GetExtension(excelPath);//获得文件扩展名 string conn = ""; if (fileExt == ".xls") { conn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + excelPath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; } else { conn = "Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source =" + excelPath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'"; } OleDbConnection con = new OleDbConnection(conn); DataTable dt = new DataTable(); OleDbDataAdapter da = new OleDbDataAdapter("select * from [Admin$]", con); //查询表名文件Admin的数据表 con.Open(); da.Fill(dt); //填充到dt con.Close(); foreach (DataRow dr in dt.Rows) { MessageBox.Show(dr["管理员编号"].ToString()); } }