直接让C#读Excel,然后对"供应商" select distinct,然后分别对每个供应商做表。这样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;
- }
【编辑推荐】