日期:2014-05-20 浏览次数:20799 次
protected void btnOK_Click(object sender, EventArgs e) { if (fuPath.HasFile) { string path = fuPath.PostedFile.FileName.ToString(); string[] pathArray = path.Split('\\'); string name = pathArray[pathArray.Length - 1]; string endName = DateTime.Now.ToString("yyMMddHHmmss") + name; string endPath = HttpContext.Current.Server.MapPath("~/Excel/") + endName; fuPath.PostedFile.SaveAs(endPath); DataSet ds = ExcelToDataSet(endPath); if (SqlHelper.HasRow(ds)) { string error = ""; #region for for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { #region Check string typeNo = ds.Tables[0].Rows[i]["xx"].ToString().Trim(); string typeName = ds.Tables[0].Rows[i]["ccc"].ToString().Trim(); string pTypeNo = ds.Tables[0].Rows[i]["dd"].ToString().Trim(); string pTypeName = ds.Tables[0].Rows[i]["eee"].ToString().Trim(); string remark = ds.Tables[0].Rows[i]["fff"].ToString().Trim(); if (typeNo.Length > 100) typeNo = typeNo.Substring(0, 100); if (typeName.Length > 100) typeName = typeName.Substring(0, 100); if (pTypeName.Length > 50) pTypeName = pTypeName.Substring(0, 50); if (remark.Length > 100) remark = remark.Substring(0, 100); #endregion #region Linq TabAssetsType p = db.TabAssetsType.FirstOrDefault(c => c.TypeNo == typeNo); if (p == null) { TabAssetsType tabAsstype = new TabAssetsType(); tabAsstype.TypeNo = FormatCom.String(typeNo); tabAsstype.TypeName = FormatCom.String(typeName); tabAsstype.PTypeNo = FormatCom.String(pTypeNo); tabAsstype.PTypeName = FormatCom.String(pTypeName); tabAsstype.IsState = 0; tabAsstype.Remark = FormatCom.String(remark); db.TabAssetsType.InsertOnSubmit(tabAsstype); } else { //error += @"xx(" + typeNo + ")已存在!\r\n"; } #endregion } #endregion try { db.SubmitChanges(); db.ExecuteCommand("update TabAssetsType set TypeNo = TypeNo"); error += @"导入成功!\r\n"; MessageBox(error); } catch (Exception ex) { MessageBox("导入失败!"); } } else { MessageBox("该文件中没有xx信息,请检查模板是否正确!"); return; } } else { MessageBox("请选择要导入的文件!"); return; } } public DataSet ExcelToDataSet(string Path) { DataSet ds = new DataSet(); try { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn); myCommand.Fill(ds, "TabAssetsType"); return ds; } catch { MessageBox("支持Excel2003的导入不支持2007!"); } return ds; }