//创建文件数据库,并添加50条数据。 void CreateTable() { Response.Write("文章见:http://www.cnblogs.com/cyq1162/p/3443244.html <hr />"); if (DBTool.ExistsTable(tableName)) { using (MAction action = new MAction(tableName)) { if (action.Fill("order by id desc")) { action.Delete("id<=" + action.Get <int>(0)); } } //DBTool.DropTable(tableName); } else { MDataColumn mdc = new MDataColumn(); mdc.Add("ID", SqlDbType.Int, true); mdc.Add("Name"); mdc.Add("CreateTime", SqlDbType.DateTime); DBTool.CreateTable(tableName, mdc); } MDataTable dt = new MDataTable(tableName); dt.Columns = DBTool.GetColumns(tableName); for (int i = 0; i < 60; i++) { dt.NewRow(true).Set(1, "Name_" + i).Set(2, DateTime.Now.AddSeconds(i)); } dt.AcceptChanges(AcceptOp.Insert); }
private static void FillTable(string objName, string objCode, MDataTable dt) { Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle; MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(objCode)); MCellStruct cell = null; int jointPrimaryCount = mdc.JointPrimary.Count; for (int i = 0; i < mdc.Count; i++) { cell = mdc[i]; MDataRow row = dt.NewRow(); row.Set(Config_Grid.ObjName, objName); row.Set(Config_Grid.Field, cell.ColumnName); row.Set(Config_Grid.Title, fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName); row.Set(Config_Grid.Hidden, i == 0 && jointPrimaryCount < 2); row.Set(Config_Grid.OrderNum, (i + 1) * 10); row.Set(Config_Grid.Width, 100); row.Set(Config_Grid.Sortable, i > 0); row.Set(Config_Grid.Import, i > 0); row.Set(Config_Grid.Export, i > 0); row.Set(Config_Grid.Colspan, 1); row.Set(Config_Grid.Rowspan, 1); row.Set(Config_Grid.Edit, i > 0 || jointPrimaryCount > 1); row.Set(Config_Grid.Frozen, i < 4); row.Set(Config_Grid.Align, "center"); string value = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + (cell.IsCanNull ? ",0" : ",1") + (cell.IsPrimaryKey ? ",1" : ",0"); row.Set(Config_Grid.DataType, value); if (i == 0) { if (jointPrimaryCount < 2) { row.Set(Config_Grid.Formatter, "#"); } } else { switch (DataType.GetGroup(cell.SqlType)) { case 2: row.Set(Config_Grid.Formatter, "dateFormatter"); break; case 3: row.Set(Config_Grid.Formatter, "boolFormatter"); break; default: if (cell.MaxSize > 50) { row.Set(Config_Grid.Formatter, "stringFormatter"); } break; } } dt.Rows.Add(row); } }
private static void FillTable(string objName, MDataTable dt) { string formatObjName = objName.Contains(" ") ? objName.Substring(objName.LastIndexOf(' ')).Trim() : objName; Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle; MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(objName)); MCellStruct cell = null; for (int i = 0; i < mdc.Count; i++) { cell = mdc[i]; MDataRow row = dt.NewRow(); row["ObjName"].Value = formatObjName; row["Field"].Value = cell.ColumnName; row["Title"].Value = fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName; row["Hidden"].Value = i == 0;//隐藏主键 row["Formatter"].Value = i == 0 ? "#" : ""; row["OrderNum"].Value = (i + 1) * 10; row["Width"].Value = 100;//第一个主键列<10,则由图标个数*36 自动控制。 row["Sortable"].Value = i > 0; row["Import"].Value = i > 0 && !cell.IsCanNull; row["Export"].Value = true; row["Edit"].Value = i > 0; row["Frozen"].Value = i < 4; row["Align"].Value = "center"; row["DataType"].Value = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + "," + (cell.IsCanNull ? 0 : 1); if (i > 0) { switch (DataType.GetGroup(cell.SqlType)) { //case 1: // row["DataType"].Value = "int"; // break; case 2: //row["DataType"].Value = "datetime"; row["Formatter"].Value = "dateFormatter"; break; case 3: //row["DataType"].Value = "bool"; row["Formatter"].Value = "boolFormatter"; break; default: //row["DataType"].Value = "string"; if (cell.MaxSize > 50) { row["Formatter"].Value = "stringFormatter"; } break; } } dt.Rows.Add(row); } }
private static void FillTable(string objName, MDataTable dt) { string formatObjName = objName.Contains(" ") ? objName.Substring(objName.LastIndexOf(' ')).Trim() : objName; Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle; MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(objName)); MCellStruct cell = null; for (int i = 0; i < mdc.Count; i++) { cell = mdc[i]; MDataRow row = dt.NewRow(); row.Set(Config_Grid.ObjName, formatObjName); row.Set(Config_Grid.Field, cell.ColumnName); row.Set(Config_Grid.Title, fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName); row.Set(Config_Grid.Hidden, i == 0); row.Set(Config_Grid.OrderNum, (i + 1) * 10); row.Set(Config_Grid.Width, 100); row.Set(Config_Grid.Sortable, i > 0); row.Set(Config_Grid.Import, i > 0); row.Set(Config_Grid.Export, i > 0); row.Set(Config_Grid.Colspan, 1); row.Set(Config_Grid.Rowspan, 1); row.Set(Config_Grid.Edit, i > 0); row.Set(Config_Grid.Frozen, i < 4); row.Set(Config_Grid.Align, "center"); row.Set(Config_Grid.DataType, DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + "," + (cell.IsCanNull ? 0 : 1)); if (i == 0) { row.Set(Config_Grid.Formatter, "#"); } else { switch (DataType.GetGroup(cell.SqlType)) { case 2: row.Set(Config_Grid.Formatter, "dateFormatter"); break; case 3: row.Set(Config_Grid.Formatter, "boolFormatter"); break; default: if (cell.MaxSize > 50) { row.Set(Config_Grid.Formatter, "stringFormatter"); } break; } } dt.Rows.Add(row); } }
private void btnCreateData_Click(object sender, EventArgs e) { MDataTable dt = new MDataTable("MyTable"); dt.Columns.Add("ID", SqlDbType.Int, true, false, 11, true, null); dt.Columns.Add("Name"); dt.Columns.Add("Password"); mdc = dt.Columns; for (int i = 0; i < 10; i++) { dt.NewRow(true).Set(0, i + 1).Set(1, "Name" + i).Set(2, i); } dt.Bind(dgvData); }
private void AddSuperAdminPromission(string menuID, string actionIDs) { if (!string.IsNullOrEmpty(actionIDs)) { MDataTable dt = new MDataTable(TableNames.Sys_RoleAction.ToString()); dt.Columns.Add("RoleID"); dt.Columns.Add("MenuID"); dt.Columns.Add("ActionID"); foreach (string actionID in actionIDs.Split(',')) { dt.NewRow(true).Set(0, UserAuth.SuperAdminRoleID) .Set(1, menuID).Set(2, actionID); } dt.AcceptChanges(AcceptOp.Insert); } }
private void AddSuperAdminPromission(string menuid, string actionids) { if (!string.IsNullOrEmpty(actionids)) { MDataTable dt = new MDataTable(U_AriesEnum.Sys_RoleAction.ToString()); dt.Columns.Add("RoleID"); dt.Columns.Add("MenuID"); dt.Columns.Add("ActionID"); foreach (string actionid in actionids.Split(',')) { dt.NewRow(true).Set(0, UserAuth.SuperAdminRoleID) .Set(1, menuid).Set(2, actionid); } dt.AcceptChanges(AcceptOp.Insert, CrossDb.GetConn(U_AriesEnum.Sys_RoleAction.ToString())); } }
private void btnRemove_Click(object sender, EventArgs e) { MDataTable delDt = dt.GetSchema(false); for (int i = 0; i < dgView.Rows.Count; i++) { if (Convert.ToString(dgView.Rows[i].Cells[0].Value) == "True") { dgView.Rows.RemoveAt(i); delDt.NewRow(true).LoadFrom(dt.Rows[i]); } } dgView.Refresh(); delDt.AcceptChanges(AcceptOp.Delete); delDt.AcceptChanges(AcceptOp.Insert | AcceptOp.Truncate); }
/// <summary> /// 接收Post过来的Json权限 /// </summary> /// <returns></returns> private MDataTable GetTable(string roleID) { MDataTable rowAction = new MDataTable(TableNames.Sys_RoleAction.ToString()); rowAction.Columns.Add("RoleID", SqlDbType.NVarChar); rowAction.Columns.Add("MenuID", SqlDbType.NVarChar); rowAction.Columns.Add("ActionID", SqlDbType.NVarChar); MDataTable dt; if (Query <string>("all") == "1") { if (UserAuth.IsSuperAdmin) { dt = SysMenu.MenuTable; } else { dt = SysMenu.GetUserMenu(true); } } else { dt = MDataTable.CreateFrom(Query <string>("data")); } if (dt != null && dt.Rows.Count > 0) { string menuID = string.Empty; foreach (MDataRow row in dt.Rows) { menuID = row.Get <string>("MenuID"); if (!string.IsNullOrEmpty(menuID)) { string[] ActionIDs = row.Get <string>("ActionIDs", "").Split(','); foreach (string actionID in ActionIDs) { if (!string.IsNullOrEmpty(actionID)) { rowAction.NewRow(true).Set(0, roleID).Set(1, menuID).Set(2, actionID); } } } } } return(rowAction); }
public MDataTable Load(string json) { MDataTable table = new MDataTable("loadFromJson"); if (!string.IsNullOrEmpty(json) && json.Length > 30 && json.StartsWith("{") && json.IndexOf(',') > -1 && json.EndsWith("}")) { try { int start=json.IndexOf(":[{") + 2; string data = json.Substring(start, json.LastIndexOf("]}") - start); data = data.Replace("\\}", "#100#").Replace("\\,", "#101#").Replace("\\:,", "#102#"); bool isOK=false; if (!string.IsNullOrEmpty(data)) { string[] items = data.Replace("{",string.Empty).Split('}');//分隔每一行 string item = string.Empty, key = string.Empty, value = string.Empty; for (int i = 0; i < items.Length; i++)//循环每一行数据 { item = items[i].Replace("#100#", "\\}").Trim(','); if (string.IsNullOrEmpty(item)) { continue; } string[] keyValues = item.Split(','); string keyValue = string.Empty; if (i == 0) { for (int j = 0; j < keyValues.Length; j++) { keyValue = keyValues[j].Replace("#101#", "\\,"); key = keyValue.Split(':')[0].Trim('\'', '\"'); table.Columns.Add(key, SqlDbType.NVarChar); } isOK=true; } if (isOK) { MDataRow row = table.NewRow(); for (int k = 0; k < keyValues.Length; k++) { keyValue = keyValues[k].Replace("#101#", "\\,"); if (keyValue.IndexOf(':') > -1) { value = keyValue.Substring(keyValue.IndexOf(':')+1).Replace("#102#", "\\:").Trim('\'', '\"'); row[k].Value = value; } } table.Rows.Add(row); } } } } catch { return table; } } return table; }
/// <summary> /// 读取数据库所有表 /// </summary> /// <param name="key">关键字</param> /// <param name="filter">过滤条件值</param> /// <returns></returns> public static MDataTable Get(string key, string filter) { MDataTable dt = null; SortedDictionary <string, string> newDic = new SortedDictionary <string, string>(); switch (key) { case "C_SYS_Table": if (!string.IsNullOrEmpty(filter)) // 有过滤条件 { string[] items = filter.Split(','); //指定数据库链接条件 foreach (string item in items) { if (item.EndsWith("Conn")) //当成链接处理 { int dbHash = DBInfo.GetHashCode(item); if (DBTool.DataBases.ContainsKey(dbHash)) { foreach (var table in DBTool.DataBases[dbHash].Tables) { newDic.Add(table.Value.Name, table.Value.Name); } } } else //当成普通表名处理 { newDic.Add(item, item); } } } else { foreach (var db in DBTool.DataBases) { foreach (var table in db.Value.Tables) { newDic.Add(table.Value.Name, table.Value.Name); } } } break; case "C_SYS_Column": if (!string.IsNullOrEmpty(filter)) { dt = new MDataTable(key); dt.Columns.Add("value"); dt.Columns.Add("text"); dt.Columns.Add("parent"); string[] items = filter.Split(','); foreach (string item in items) { MDataColumn mdc = DBTool.GetColumns(item); foreach (MCellStruct ms in mdc) { dt.NewRow(true).Set(0, ms.ColumnName).Set(1, ms.ColumnName).Set(2, item); } } } break; } if (dt == null) { dt = MDataTable.CreateFrom(newDic); dt.Columns[0].ColumnName = "value"; dt.Columns[1].ColumnName = "text"; if (dt.Columns.Count > 2) { dt.Columns[2].ColumnName = "parent"; } } return(dt); }
/// <summary> /// 读取数据库所有表 /// </summary> /// <param name="key">关键字</param> /// <param name="filter">过滤条件值</param> /// <returns></returns> public static MDataTable Get(string key, string filter) { MDataTable dt = null; SortedDictionary <string, string> newDic = new SortedDictionary <string, string>(); switch (key) { case "C_SYS_Table": if (!string.IsNullOrEmpty(filter)) // 有过滤条件 { string[] items = filter.Split(','); if (items.Length == 1 && items[0].EndsWith("Conn")) { if (CrossDb.DbTables.ContainsKey(filter)) { foreach (var item in CrossDb.DbTables[filter]) { newDic.Add(item.Key, item.Key); } } } else { foreach (string item in items) { newDic.Add(item, item); } } } else { foreach (var tableDic in CrossDb.DbTables) { foreach (var item in tableDic.Value) { newDic.Add(item.Key, item.Key); } } } break; case "C_SYS_Column": if (!string.IsNullOrEmpty(filter)) { dt = new MDataTable(key); dt.Columns.Add("value"); dt.Columns.Add("text"); dt.Columns.Add("parent"); string[] items = filter.Split(','); foreach (string item in items) { MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(item)); foreach (MCellStruct ms in mdc) { dt.NewRow(true).Set(0, ms.ColumnName).Set(1, ms.ColumnName).Set(2, item); } } } break; } if (dt == null) { dt = MDataTable.CreateFrom(newDic); dt.Columns[0].ColumnName = "value"; dt.Columns[1].ColumnName = "text"; if (dt.Columns.Count > 2) { dt.Columns[2].ColumnName = "parent"; } } return(dt); }
private static void FillTable(string objName, string objCode, MDataTable dt) { //Dictionary<string, string> fieldTitleDic = GridConfig.FieldTitle; string errInfo; string tableName = objCode; MDataColumn mdc = DBTool.GetColumns(tableName, null, out errInfo); if (mdc == null || mdc.Count == 0) { if (!string.IsNullOrEmpty(errInfo)) { dt.DynamicData = errInfo; } return; } MCellStruct cell = null; int jointPrimaryCount = mdc.JointPrimary.Count; for (int i = 0; i < mdc.Count; i++) { cell = mdc[i]; MDataRow row = dt.NewRow(); row.Set(Config_Grid.ObjName, objName); row.Set(Config_Grid.Field, cell.ColumnName); row.Set(Config_Grid.Title, string.IsNullOrEmpty(cell.Description) ? cell.ColumnName : cell.Description); row.Set(Config_Grid.Hidden, (i == 0 && jointPrimaryCount < 2) || i > 25);//超过25个字段,后面的都先隐藏。 row.Set(Config_Grid.OrderNum, (i + 1) * 10); row.Set(Config_Grid.Width, 100); row.Set(Config_Grid.Sortable, i > 0); row.Set(Config_Grid.Import, i > 0); row.Set(Config_Grid.Export, i > 0); row.Set(Config_Grid.Colspan, 1); row.Set(Config_Grid.Rowspan, 1); row.Set(Config_Grid.Edit, i > 0 || jointPrimaryCount > 1); row.Set(Config_Grid.Frozen, i < 4); row.Set(Config_Grid.Align, "center"); string value = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + (cell.IsCanNull ? ",0" : ",1") + (cell.IsPrimaryKey ? ",1" : ",0"); row.Set(Config_Grid.DataType, value); if (i == 0) { if (jointPrimaryCount < 2) { row.Set(Config_Grid.Formatter, "#"); } } else { switch (DataType.GetGroup(cell.SqlType)) { case 2: row.Set(Config_Grid.Formatter, "dateFormatter"); break; case 3: row.Set(Config_Grid.Formatter, "boolFormatter"); break; default: if (cell.MaxSize > 50) { row.Set(Config_Grid.Formatter, "stringFormatter"); } break; } } dt.Rows.Add(row); } }
/// <summary> /// 读取上传文件中的Excel(返回表格,如果需要导入,还需要格式化表头) /// </summary> /// <param name="workbook">Excel工作本</param> /// <param name="sheetIndex">第N个Sheet表格</param> /// <param name="isMergedCellName">是否把合并列头的名称连接起来</param> /// <param name="startIndex">开始索引</param> /// <param name="headCrossRowNum">头部跨行数(为0时自动识别)</param> /// <returns></returns> private static MDataTable ReadExcel(IWorkbook workbook, Stream stream = null, int sheetIndex = 0, int startIndex = 0, int headCrossRowNum = 0, bool isMergedCellName = false) { MDataTable dt = new MDataTable(); try { if (workbook != null) { ISheet sheet = workbook.GetSheetAt(sheetIndex); dt.TableName = sheet.SheetName; dt.DynamicData = sheet; IRow excelRow = sheet.GetRow(startIndex); int dataRowStart = startIndex; if (headCrossRowNum <= 0) { dataRowStart += 1; #region 遍历、找出(头部跨行数)最大行。用最大行进行遍历列(如果为空,往上一级找) int mIndex = 0; for (int i = 0; i < excelRow.Cells.Count; i++) { ICell cell = excelRow.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK);// .Cells[i]; if (cell.IsMergedCell) { NPOI.SS.Util.CellRangeAddress range = sheet.GetCellRange(cell);//获取范围块。 if (range != null) { dataRowStart = Math.Max(dataRowStart, range.LastRow + 1);//设置数据的读取行数。 mIndex++; i += range.LastColumn - range.FirstColumn; } } } #endregion } else { dataRowStart += headCrossRowNum; } //读取列头。 if (dataRowStart > 1) { excelRow = sheet.GetRow(dataRowStart - 1); } dt.RecordsAffected = dataRowStart; dt.Columns.CheckDuplicate = false; #region 读取列头 //if (excelRow.FirstCellNum > 0) //{ // for (int i = 0; i < excelRow.FirstCellNum; i++) // { // string columnName = "该列头为空_" + i; // dt.Columns.Add(columnName); // } //} int emptyCellCount = 0;//兼容处理错误的Excel格式(读了256个空格列) for (int i = 0; i < excelRow.Cells.Count; i++) { string columnName = string.Empty; for (int j = dataRowStart; j > startIndex; j--) { #region MyRegion IRow row = sheet.GetRow(j - 1); ICell cell; try { cell = row.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK);//不能用GetCell(i),会多出一行导致下面错误位。 } catch (Exception) { continue; } string name = cell.ToString().Trim(); // .StringCellValue.Trim(); if (!string.IsNullOrEmpty(name) && !columnName.Contains(name)) // { columnName += name + "_"; } else if (j != dataRowStart && cell.IsMergedCell) { cell = sheet.GetMergedRegion(cell);//获取范围块。 if (cell != null) { name = cell.ToString().Trim(); if (!string.IsNullOrEmpty(name) && !columnName.Contains(name)) { columnName += name + "_"; } } } if (!isMergedCellName && !string.IsNullOrEmpty(columnName)) { break; } #endregion } columnName = columnName.TrimEnd('_').Trim(); if (string.IsNullOrEmpty(columnName)) { if (emptyCellCount > 30)//连续30次空格列 { break; } emptyCellCount++; columnName = "该列头为空_" + i; } else { emptyCellCount = 0;//只要一个正常,即回归索引 } if (dt.Columns.Contains(columnName)) { columnName += "_" + i; } dt.Columns.Add(columnName); } //移除空格列 if (emptyCellCount > 0) { dt.Columns.RemoveRange(dt.Columns.Count - emptyCellCount, emptyCellCount); } if (dt.Columns.Count > 0) { dt.Conn = dt.Columns.Count.ToString();//找个变量存储实际的列的长度,在SetError中使用。(dt可能在SetError前列被变更) } #endregion ICell sheetCell; int emptyCount = 0; for (int i = dataRowStart; i <= sheet.LastRowNum; i++) { excelRow = sheet.GetRow(i); if (excelRow == null) { break; } MDataRow tbRow = dt.NewRow(); bool isOk = false; for (int j = 0; j < dt.Columns.Count; j++) { #region 读一行 sheetCell = excelRow.GetCell(j, MissingCellPolicy.RETURN_BLANK_AS_NULL); if (sheetCell != null) { string value = string.Empty; if (sheetCell.CellType == CellType.Numeric) { try { if (sheetCell.ToString().Split('/', '-').Length > 1) { value = sheetCell.DateCellValue.ToString(); } else { value = sheetCell.NumericCellValue.ToString(); } } catch { value = sheetCell.ToString(); } } else if (sheetCell.CellType == CellType.Formula) { try { /*公式不一定是Numeric的取值,也有可能是=G4 这种,然而单元格G4不是数字; * 公式单元格也有可能读取错误 #VALUE! #REF! 等*/ CellType resultType = sheetCell.CachedFormulaResultType; switch (resultType) { case CellType.Boolean: value = sheetCell.BooleanCellValue.ToString(); break; case CellType.Numeric: value = sheetCell.NumericCellValue.ToString(); break; case CellType.Blank: case CellType.Error: case CellType.Unknown: value = string.Empty; break; default: value = sheetCell.StringCellValue; break; } //value = sheetCell.NumericCellValue.ToString(); //由公式取值 } catch { } } else { value = sheetCell.ToString(); } value = value.Trim(); if (!isOk && !string.IsNullOrEmpty(value)) { isOk = true; } if (!string.IsNullOrEmpty(value))//空值当Null值处理,避免字段有Check对空值的约束 { tbRow.Set(sheetCell.ColumnIndex, value); } } #endregion } if (isOk)//忽略空行数据。 { dt.Rows.Add(tbRow); } else { if (dt.Rows.Count == 0) { dt.RecordsAffected++; } emptyCount++; if (emptyCount > 1)//超过2次空格行,跳出。 { break; } } } workbook.Close();//关闭了,dt.DynamicData带出了Sheet,还是可以后续使用(估计NPOI的没处理) } } catch (Exception err) { Log.WriteLogToTxt(err); } return(dt); }