C#中怎么读取Excel文件并存入数据库,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
protected void Page_Load(object sender, EventArgs e) { DataSet ds = ImportExcel(Server.MapPath("ExcelFile/供应商违约扣款.xls")); //C#读Excel GridView1.DataSource = ds.Tables["ExcelInfo"].DefaultView; GridView1.DataBind(); ToDataBase(ds); } private DataSet ImportExcel(string strFileName) { if (strFileName == "") return null; string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strFileName + ";" + "Extended Properties=Excel 8.0;HDR=Yes;IMEX=1"; OleDbDataAdapter ExcelDA = new OleDbDataAdapter("SELECT trim(供应商) as 供应商,零件名称,型号,批量,下线数,下线率,不合格原因,考核原因,考核金额 FROM [Sheet1$]", strConn); DataSet ExcelDs = new DataSet(); try { ExcelDA.Fill(ExcelDs, "ExcelInfo"); } catch (Exception err) { System.Console.WriteLine(err.ToString()); } return ExcelDs; } private bool ToDataBase(DataSet ds) { DataTable dtSupplier = new DataTable("dtSupplier"); DataView dv = ds.Tables[0].DefaultView; string[] column = { "供应商" }; dtSupplier = dv.ToTable(true, column); for (int i = 0; i < dtSupplier.Rows.Count; i++) { DataRow[] r = ds.Tables[0].Select("供应商='" + dtSupplier.Rows[i]["供应商"].ToString() + "'"); //插父表 for (int j = 0; j < r.Length; j++) { string ItemName = r[j]["零件名称"].ToString(); string scale = r[j]["型号"].ToString(); string batch = r[j]["批量"].ToString(); string downLine = r[j]["下线数"].ToString(); string downPercent = r[j]["下线率"].ToString(); string outReason = r[j]["不合格原因"].ToString(); string reason = r[j]["考核原因"].ToString(); string amt = r[j]["考核金额"].ToString(); //插子表 } //save } return true; }
看完上述内容,你们掌握C#中怎么读取Excel文件并存入数据库的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!