using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data.OleDb; using System.Data; using System.Text; public partial class Qunfa : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ExecleDo("upload/test4.xls"); } /// <summary> /// 读取Excel /// </summary> /// <param name="filenameurl"></param> /// <param name="tbname"></param> /// <returns></returns> public string ExecleDo(string filenameurl) { string strresult = ""; filenameurl = System.Web.HttpContext.Current.Server.MapPath("~/" + filenameurl);//Server.MapPath 获得虚拟服务器相对路径 string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); //返回Excel的构架,包括各个sheet表的名称,类型,创建时间和修改时间等。 DataTable dtSheetName = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //包含Excel表名的字符串数组 string[] strTableName = new string[dtSheetName.Rows.Count]; for (int k = 0; k < dtSheetName.Rows.Count; k++) { strTableName[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString(); } StringBuilder strExcel = new StringBuilder(); strExcel = CombExcelTxt_car_inventory();//组合sql语句 strExcel.Append(" from [" + strTableName[0] + "] where [会员名] is not null and [手机号] is not null"); // strTableName 也可换成具体的名字 [0409$] System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strExcel.ToString(), conn); DataSet ds = new DataSet(); myCommand.Fill(ds); DataTable dt = ds.Tables[0]; try { for (int i = 0; i < dt.Rows.Count; i++) { Response.Write(dt.Rows[i]["会员名"].ToString() + " " + dt.Rows[i]["手机号"].ToString() + "<br>"); } strresult = "ok"; } catch (Exception ex) { strresult = "导入数据时出错" + ex.Message.ToString(); } strConn = null; myCommand.Dispose(); conn.Close(); conn.Dispose(); return strresult; } /// <summary> /// 组合Excel语句 /// </summary> /// <returns></returns> public StringBuilder CombExcelTxt_car_inventory() { StringBuilder strExcel = new StringBuilder(); strExcel.Append("select * "); return strExcel; } }