标签:
2016-04-28 10:27:26
在各种系统中,都会有一种类型菜单表那样有上下级关系的数据表。在维护数据时,往往是令人头疼不已。一般来说,软件都会配套一个数据导入的功能。
Excel的模板是:
Excel数据转化成DataTable后
导入算法:
public ActionResult ImportData(string filename, string bzid, string lxid) { System.Data.DataTable dt; try { dt = Excel2003.ToDataTable(filename); } catch (Exception ex) { return this.MyJson(false, ex.ToString()); } int maxlevel = 0; for (int n = 0; n < dt.Columns.Count; n++) { string colname = dt.Columns[n].ColumnName; if (colname.LastIndexOf("指标", System.StringComparison.Ordinal) == -1) { break; } else { maxlevel++; } } var listError = new List<string>(); var listModel = new List<HL_JCZB>(); for (int i = 0; i < dt.Rows.Count; i++) { string errtitle = dt.TableName + " 第 " + (i + 1) + " 行: "; var model = new HL_JCZB(); model.ZFPB = 0; model.LXID = lxid; model.BZID = bzid; model.PXXH = i; string strfz = Utils.GetString(dt.Rows[i]["分值"]); if (!strfz.IsDecimal()) listError.Add(errtitle + "分值格式错误 " + strfz); else model.FZ = decimal.Parse(strfz); string strqz = Utils.GetString(dt.Rows[i]["权重"]); if (!strqz.IsDecimal()) listError.Add(errtitle + "权重格式错误 " + strqz); else model.QZ = decimal.Parse(strqz); string strxszkjz = Utils.GetString(dt.Rows[i]["显示在框架中"]); strxszkjz = string.IsNullOrEmpty(strxszkjz) ? "0" : strxszkjz; if (!strxszkjz.IsInt()) listError.Add(errtitle + "显示在框架中格式错误 " + strxszkjz); else model.KJXSPB = int.Parse(strxszkjz); string strwtgj = Utils.GetString(dt.Rows[i]["问题归集"]); strwtgj = string.IsNullOrEmpty(strwtgj) ? "0" : strwtgj; if (!strwtgj.IsInt()) listError.Add(errtitle + "问题归集格式错误 " + strwtgj); else model.WTGJPB = int.Parse(strwtgj); model.JCFF = Utils.GetString(dt.Rows[i]["检查方法"]); model.PFFF = Utils.GetString(dt.Rows[i]["评分方法"]); model.QTBZ = Utils.GetString(dt.Rows[i]["其他帮助"]); // 指标id,名称,级别,上级id for (int a = 0; a < maxlevel; a++) { string colvalue = Utils.GetString(dt.Rows[i][a]); if (!string.IsNullOrEmpty(colvalue)) { if (a == 0) { model.SJID = "ROOT"; int xh = listModel.Count(p => p.SJID == model.SJID) + 1; model.ZBMC = colvalue; model.JB = a + 1; model.ZBID = bzid + (xh < 10 ? "0" + xh : xh.ToString()); model.ZBDM = model.ZBID; model.MJPB = 1; listModel.Add(model); } else { for (int j = listModel.Count - 1; j >= 0; j--) { if (listModel[j].JB < a + 1) { model.SJID = listModel[j].ZBID; listModel[j].MJPB = 0; int xh = listModel.Count(p => p.SJID == model.SJID) + 1; model.ZBMC = colvalue; model.JB = a + 1; model.ZBID = model.SJID + (xh < 10 ? "0" + xh : xh.ToString()); model.ZBDM = model.ZBID; model.MJPB = 1; listModel.Add(model); break; } } } } } } var states = new List<DBState>(); for (int i = 0; i < listModel.Count; i++) { states.Add(new DBState() { Name = listModel[i].MAP_INSERT, Param = listModel[i], Type = ESqlType.INSERT }); } DB.Execute(states); return this.MyJson(true, "导入成功"); }
标签:
原文地址:http://www.cnblogs.com/chenrh/p/5441667.html