/****************************** * 说明:GridControlEx相关扩展 * 创建人:龚宇超 * 创建日期:2017-11-14 * 修改人: * 修改日期: * 修改备注: * 版本:1.0.0.0 ******************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using DevExpress.XtraGrid; using System.Windows.Forms; using Lskj.Data; using Lskj.Util; using DevExpress.XtraGrid.Columns; using System.Data; using DevExpress.XtraGrid.Views.Grid; //using NPOI.SS.UserModel; using System.IO; using Lskj.Model; using DevExpress.Utils.Menu; using System.Collections; using Lskj.Business.Impl; //using NPOI.HSSF.UserModel; //using NPOI.HSSF.Record.CF; using DevExpress.XtraPrintingLinks; using Lskj.Business; using DevExpress.XtraTreeList; using Lskj.Control.Model.MenuStrip; using DevExpress.XtraTreeList.Columns; using System.Text.RegularExpressions; using DevExpress.XtraEditors; using Lskj.Core; using DevExpress.XtraGrid.Views.BandedGrid; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.Record.CF; using DevExpress.XtraPrinting; using DevExpress.XtraEditors.Repository; using System.Drawing; using DevExpress.XtraTab; using NPOI.SS.Util; using DevExpress.Data; using DevExpress.Data.Filtering; using System.Data.SqlClient; using DevExpress.Utils; namespace Lskj.Control.Model { /// /// GridControlEx相关扩展 /// public static class GridExtend { private static Dictionary ValueGridColumnTable; private static Dictionary LookupParentKey; private static List _checkColumns; private static string _treeColumnName; private static string exportAddress;//导出全部时的存放地址 private static string suffix;//导出全部时的后缀 /// /// 无需更新的列 /// private static string[] _disUpdateColumns = { "id" }; /// /// 缓存列对象 /// private static List ColumnList = new List(); /// /// 缓存列对象名字 /// public static List ColumnNameList = new List(); /// /// 说明:扩展DXMenuItemCollection批量添加菜单 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// /// The items. /// The collection. public static void AddRange(this DXMenuItemCollection items, IEnumerable collection) where T : DXMenuItem { foreach (T item in collection) { items.Add(item); } } /// /// 说明:普通表格执行保存存入数据库 /// 创建人:王一帆 /// 创建日期:2020-12-28 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// /// The items. /// The collection. public static void NewGridSaveData(this GridControl gcMain, string tableName, GridView BaseColumn) { string _parmaryKey = BaseImpl.GetPrimaryKey(tableName); GridColumnCollection _gridColumns = BaseColumn.Columns; string BaseSql = string.Empty; if (string.IsNullOrEmpty(tableName)) { MessageUtil.Show(ResourceKeys.MenuTableNameIsNull); return; } List mList = new List(); DataRow[] modifiedRows = (gcMain.DataSource as DataTable).Rows .Cast() .Where(x => x.RowState == DataRowState.Modified || x.RowState == DataRowState.Added) .ToArray(); if (modifiedRows == null || modifiedRows.Length == 0) { MessageUtil.Show(ResourceKeys.UnUpdateData); return; } else { DataColumnCollection columns = gcMain.DataSourceTable().Columns; foreach (DataRow row in modifiedRows) { string updateSql = "update {0} set {1} where {2}='{3}';"; string insertSql = "insert into {0}({1}) values({2});"; string updateFields = string.Empty; string insertFields = string.Empty; string insertValues = string.Empty; //BaseSaveModel model = new BaseSaveModel() //{ // MenuCode = this.Model.ModuleCode, // TableName = tableName, // KeyField = _parmaryKey, // NewVer = this.SysModel.NewVer //}; foreach (DataColumn col in columns) { GridColumn gridColumn = _gridColumns.Cast().FirstOrDefault(x => x.FieldName == col.ColumnName); // 区分大小写匹配列 if (gridColumn != null && col.ColumnName != _parmaryKey && !_disUpdateColumns.Contains(col.ColumnName)) { if (row.RowState == DataRowState.Modified) { if ((col.DataType == typeof(DateTime)) && (row[col.ColumnName] + "" == "")) updateFields += string.Format("[{0}]=null,", col.ColumnName); else updateFields += string.Format("[{0}]='{1}',", col.ColumnName, (row[col.ColumnName] + "").Replace("'", "''")); } else if (row.RowState == DataRowState.Added || (row.RowState == DataRowState.Modified)) { // 动态生成列,保存时默认全部为新增 string fieldValue = string.Empty; fieldValue = (row[col.ColumnName] + "").Replace("'", "''"); insertFields += "[" + col.ColumnName + "],"; if (!string.IsNullOrWhiteSpace(fieldValue)) { insertValues += col.DataType == typeof(DateTime) ? "'" + Convert.ToDateTime(fieldValue).ToString("yyyy-MM-dd HH:mm:ss") + "'," : "'" + fieldValue + "',"; } else { if (col.DataType == typeof(Decimal) || col.DataType == typeof(Int32)) insertValues += "0,"; else if (col.DataType == typeof(DateTime)) insertValues += "NULL,"; else insertValues += "'',"; } } } } // 检查是否保存主键字段 if (row.RowState == DataRowState.Added && !insertFields.Contains(_parmaryKey) && !"ID".Equals(_parmaryKey, StringComparison.OrdinalIgnoreCase)) { // 跳过自动增长列处理 if (BaseImpl.GetResult(string.Format("select columnproperty(object_id('{0}'),'{1}','IsIdentity')", tableName, _parmaryKey)) + "" == "0") { insertFields += _parmaryKey + ","; insertValues += "'" + row[_parmaryKey] + "',"; } } updateFields = updateFields.TrimEnd(','); insertFields = insertFields.TrimEnd(','); insertValues = insertValues.TrimEnd(','); if (!string.IsNullOrEmpty(updateFields)) { BaseSql = string.Format(updateSql, tableName, updateFields, _parmaryKey, row[_parmaryKey]); } if (!string.IsNullOrEmpty(insertFields)) { BaseSql = string.Format(insertSql, tableName, insertFields, insertValues); } mList.Add(BaseSql); } try { // 批量保存数据 if (SaveBaseGridData(mList)) { (gcMain.DataSource as DataTable).AcceptChanges(); MessageUtil.Show(ResourceKeys.SaveSuccess); } else { StringBuilder builder = new StringBuilder(); builder.Append("失败列表\r\n"); //foreach (string item in mList) //{ // if (!string.IsNullOrEmpty(item.FaultMsg)) // builder.Append("原因:" + item.FaultMsg + "\r\n"); ; //} MessageUtil.Show(builder.ToString()); } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); //MessageUtil.Show(ex); } } } /// /// 说明:批量保存基础档案 /// 创建人:龚宇超 /// 创建日期:2017-11-08 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The models. /// true if XXXX, false otherwise. public static bool SaveBaseGridData(List models) { int resultCount = SaveBasePanelData(models); return resultCount == models.Count; } /// /// 说明:保存基础档案 /// 创建人:王一帆 /// 创建日期:2020-05-25 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// System.Int32. public static int SaveBasePanelData(List model) { int Count = 0; foreach (string sql in model) { Count = SqlHelper.ExecuteNonQuery(sql) > 0 ? Count + 1 : Count; } return Count; } /// /// 说明:GridControl数据行 /// 创建人:龚宇超 /// 创建日期:2017-11-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. public static int DataRowCount(this GridControlEx control) { try { return (control.GridControl.DataSource as DataTable).Rows.Count; } catch (Exception) { } return 0; } /// /// 说明:获取所有RowHandler /// 创建人:龚宇超 /// 创建日期:2018-03-21 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// System.Int32[]. public static int[] RowHandlers(this GridView gridView) { if (gridView == null) return new int[] { }; DataTable table = gridView.GridControl.DataSourceTable().TrimDeleteRows().TrimEmptyRows(); int[] rows = new int[table.Rows.Count]; for (int i = 0; i < table.Rows.Count; i++) { rows[i] = gridView.GetRowHandle(i); } return rows; } /// /// 说明:检测是否某列是否正处于排序状态 /// 创建人:龚宇超 /// 创建日期:2018-06-06 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. public static bool HasSortColumn(this GridView gridView, string columnName = "") { if (string.IsNullOrEmpty(columnName)) { var columns = gridView.Columns.Where(x => x.SortOrder != DevExpress.Data.ColumnSortOrder.None); return columns == null || columns.Count() != 0; } else { var columns = gridView.Columns.Where(x => x.SortOrder != DevExpress.Data.ColumnSortOrder.None && x.FieldName == columnName); return columns == null || columns.Count() != 0; } } /// /// 说明:表格必须录入验证 /// 创建人:龚宇超 /// 创建日期:2018-01-04 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// 不能为空的字段. /// true if XXXX, false otherwise. public static bool ValidateNullRequired(this GridView gridView, DataRow[] nullFields) { DataTable dtBillItem = gridView.GridControl.DataSource as DataTable; if (dtBillItem == null) return false; DataColumnCollection dtBillRow = dtBillItem.Columns; GridColumnCollection gridColumns = gridView.Columns; if (dtBillItem != null && dtBillItem.Rows.Count > 0) { DataRow[] modifiedRows = dtBillItem.Rows .Cast() .Where(x => x.RowState == DataRowState.Modified || x.RowState == DataRowState.Added) .ToArray(); foreach (DataRow drGrid in modifiedRows) { foreach (DataRow dr in nullFields) { string fieldName = dr["fieldName"] + ""; string fieldText = dr["username"] + ""; if (string.IsNullOrEmpty(drGrid[fieldName] + "")) { MessageUtil.Show(string.Format(ResourceKeys.NullField, fieldText)); gridView.Focus(); gridView.FocusedRowHandle = dtBillItem.Rows.IndexOf(drGrid); gridView.FocusedColumn = gridColumns[fieldName]; gridView.SelectCell(gridView.FocusedRowHandle, gridColumns[fieldName]); gridView.ShowEditorByMouse(); return false; } } } } return true; } /// /// 说明:单据审核明细表格必须录入验证 /// 创建人:曹屹峰 /// 创建日期:2023-09-20 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// 不能为空的字段名. /// true if XXXX, false otherwise. public static bool ValidateNullRequired(this GridView gridView, List DetailsRequired) { DataTable dtBillItem = gridView.GridControl.DataSource as DataTable; if (dtBillItem == null) return false; DataColumnCollection dtBillRow = dtBillItem.Columns; GridColumnCollection gridColumns = gridView.Columns; if (dtBillItem != null && dtBillItem.Rows.Count > 0) { //DataRow[] modifiedRows = dtBillItem.Rows // .Cast() // .Where(x => x.RowState == DataRowState.Modified || x.RowState == DataRowState.Added) // .ToArray(); foreach (DataRow drGrid in dtBillItem.Rows) { foreach (string requiredName in DetailsRequired) { GridColumn gridColumn = gridColumns[requiredName]; if (gridColumn != null) { string fieldName = gridColumn.FieldName; string fieldText = gridColumn.Caption; if (string.IsNullOrEmpty(drGrid[fieldName] + "")) { MessageUtil.Show(string.Format(ResourceKeys.NullField, fieldText)); gridView.Focus(); gridView.FocusedRowHandle = dtBillItem.Rows.IndexOf(drGrid); gridView.FocusedColumn = gridColumns[fieldName]; gridView.SelectCell(gridView.FocusedRowHandle, gridColumns[fieldName]); gridView.ShowEditorByMouse(); return false; } } } } } return true; } /// /// 说明:多表头保存个性化列 /// 创建人:王一帆 /// 创建日期:2022-05-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// true if XXXX, false otherwise. public static bool SaveCustomColumnToDatabase(this BandedGridView gridView, string key) { try { if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "IfFixColumn")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "FieldText")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add FieldText varchar(100)"); } // 保存管理员、普通用户列均保存到P_systemGridConfigTab表中,不操作系统表. StringBuilder sBuilder = new StringBuilder(); bool isGroupIndex = false; bool isFilterInfo = false; bool isDisplayFiltering = false; string saveFieldName = string.Empty; //分组号 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "GroupIndex")) { isGroupIndex = true; saveFieldName = ",GroupIndex"; } //列筛选条件 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "FilterInfo")) { isFilterInfo = true; saveFieldName += ",FilterInfo"; } //是否显示筛选行 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "DisplayFiltering")) { isDisplayFiltering = true; saveFieldName += ",DisplayFiltering"; } foreach (BandedGridColumn col in gridView.Columns) { string fieldValue = string.Empty; if (isGroupIndex) { fieldValue = ",'" + col.GroupIndex + "'"; } if (isFilterInfo) { fieldValue += ",'" + col.FilterInfo.FilterString.Replace("'", "''") + "'"; } if (isDisplayFiltering) { fieldValue += gridView.OptionsView.ShowAutoFilterRow ? ",'1'" : ",'0'"; } GridColumnModel model = col.Tag as GridColumnModel; if (model == null) continue; string tempSql = string.Format(@"insert into {8}(formkey,fieldname,username,orderid,isvisible,operatorid,operatorName,operatedate,fieldWidth,IfFixColumn,FieldText {11}) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',getdate(),'{7}','{9}','{10}' {12});", key, col.FieldName, col.Caption, col.VisibleIndex, Convert.ToInt32(col.Visible), ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, col.Width, ResourceKeys.SettingTableName, col.OwnerBand != null ? col.OwnerBand.Fixed == DevExpress.XtraGrid.Columns.FixedStyle.Left : false, model.FieldText, saveFieldName, fieldValue); sBuilder.Append(tempSql); } return BaseImpl.ExecSqlValue(sBuilder.ToString()) > 0; } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } return false; } /// /// 说明:更新个性列 /// 创建人:王一帆 /// 创建日期:2022-05-19 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// true if XXXX, false otherwise. public static bool UpdateCustomColumnToDatabase(this BandedGridView gridView, string key) { if (string.IsNullOrEmpty(key)) return false; if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "IfFixColumn")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "FieldText")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add FieldText varchar(100)"); } string sqlValue = string.Format("select * from {0} where formKey='{1}' and OperatorId='{2}'", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserId); DataTable customTable = SqlHelper.ExecuteDataTable(sqlValue); StringBuilder sBuilder = new StringBuilder(); bool isGroupIndex = false; bool isFilterInfo = false; bool isDisplayFiltering = false; string saveFieldName = string.Empty; //分组号 if (customTable.Columns.Contains("GroupIndex")) { isGroupIndex = true; saveFieldName = ",GroupIndex"; } //列筛选条件 if (customTable.Columns.Contains("FilterInfo")) { isFilterInfo = true; saveFieldName += ",FilterInfo"; } //是否显示筛选行 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "DisplayFiltering")) { isDisplayFiltering = true; saveFieldName += ",DisplayFiltering"; } foreach (BandedGridColumn col in gridView.Columns) { string fieldValue = string.Empty; string updateField = string.Empty; if (isGroupIndex) { fieldValue = ",'" + col.GroupIndex + "'"; updateField = string.Format(" ,GroupIndex='{0}' ", col.GroupIndex); } if (isFilterInfo) { fieldValue += ",'" + col.FilterInfo.FilterString.Replace("'", "''") + "'"; updateField += string.Format(" ,FilterInfo='{0}' ", col.FilterInfo.FilterString.Replace("'", "''")); } if (isDisplayFiltering) { fieldValue += gridView.OptionsView.ShowAutoFilterRow ? ",'1'" : ",'0'"; updateField += gridView.OptionsView.ShowAutoFilterRow ? " ,DisplayFiltering='1' " : " ,DisplayFiltering='0' "; } GridColumnModel model = col.Tag as GridColumnModel; DataRow a = customTable.Rows.Cast().FirstOrDefault(x => col.Name.Equals(x["fieldName"] + "", StringComparison.OrdinalIgnoreCase)); string tempSql = a == null ? string.Format(@"insert into {8}(formkey,fieldname,username,orderid,isvisible,operatorid,operatorName,operatedate,fieldWidth,IfFixColumn,FieldText {11}) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',getdate(),'{7}','{9}','{10}' {12});", key, col.FieldName, col.Caption, col.VisibleIndex, Convert.ToInt32(col.Visible), ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, col.Width, ResourceKeys.SettingTableName, col.OwnerBand.Fixed == DevExpress.XtraGrid.Columns.FixedStyle.Left, model.FieldText, saveFieldName, fieldValue) : string.Format(@"update {6} set orderid='{0}',fieldWidth='{1}',isvisible={2},IfFixColumn='{7}' {8} where formkey='{3}' and fieldname='{4}' and operatorid='{5}';", col.VisibleIndex, col.Width, Convert.ToInt32(col.Visible), key, col.FieldName, ERPInfo.Instance.UserId, ResourceKeys.SettingTableName, col.OwnerBand != null ? col.OwnerBand.Fixed == DevExpress.XtraGrid.Columns.FixedStyle.Left : false, updateField); sBuilder.Append(tempSql); } return BaseImpl.ExecSqlValue(sBuilder.ToString()) > 0; } /// /// 说明:保存个性化列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// true if XXXX, false otherwise. public static bool SaveCustomColumnToDatabase(this GridView gridView, string key) { try { if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "IfFixColumn")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } // 保存管理员、普通用户列均保存到P_systemGridConfigTab表中,不操作系统表. StringBuilder sBuilder = new StringBuilder(); bool isGroupIndex = false; bool isFilterInfo = false; bool isDisplayFiltering = false; string saveFieldName = string.Empty; //分组号 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "GroupIndex")) { isGroupIndex = true; saveFieldName = ",GroupIndex"; } //列筛选条件 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "FilterInfo")) { isFilterInfo = true; saveFieldName += ",FilterInfo"; } //是否显示筛选行 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "DisplayFiltering")) { isDisplayFiltering = true; saveFieldName += ",DisplayFiltering"; } foreach (GridColumn col in gridView.Columns) { string fieldValue = string.Empty; if (isGroupIndex) { fieldValue = ",'" + col.GroupIndex + "'"; } if (isFilterInfo) { fieldValue += ",'" + col.FilterInfo.FilterString.Replace("'", "''") + "'"; } if (isDisplayFiltering) { fieldValue += gridView.OptionsView.ShowAutoFilterRow ? ",'1'" : ",'0'"; } string tempSql = string.Format(@"insert into {8}(formkey,fieldname,username,orderid,isvisible,operatorid,operatorName,operatedate,fieldWidth,IfFixColumn {10}) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',getdate(),'{7}','{9}' {11});", key, col.FieldName, col.Caption.Replace("'", "''"), col.VisibleIndex, Convert.ToInt32(col.Visible), ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, col.Width, ResourceKeys.SettingTableName, col.Fixed == DevExpress.XtraGrid.Columns.FixedStyle.Left, saveFieldName, fieldValue); sBuilder.Append(tempSql); } return BaseImpl.ExecSqlValue(sBuilder.ToString()) > 0; } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } return false; } /// /// 说明:保存树表格个性化列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// true if XXXX, false otherwise. public static bool SaveCustomColumnToDatabase(this TreeList gridView, string key) { if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "IfFixColumn")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } // 保存管理员、普通用户列均保存到P_systemGridConfigTab表中,不操作系统表. StringBuilder sBuilder = new StringBuilder(); foreach (TreeListColumn col in gridView.Columns) { string tempSql = string.Format(@"insert into {8}(formkey,fieldname,username,orderid,isvisible,operatorid,operatorName,operatedate,fieldWidth,IfFixColumn) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',getdate(),'{7}','{9}');", key, col.FieldName, col.Caption, col.VisibleIndex, Convert.ToInt32(col.Visible), ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, col.Width, ResourceKeys.SettingTableName, col.Fixed == DevExpress.XtraTreeList.Columns.FixedStyle.Left); sBuilder.Append(tempSql); } return BaseImpl.ExecSqlValue(sBuilder.ToString()) > 0; } /// /// 说明:更新个性列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// true if XXXX, false otherwise. public static bool UpdateCustomColumnToDatabase(this GridView gridView, string key) { if (string.IsNullOrEmpty(key)) return false; if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "IfFixColumn")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } string sqlValue = string.Format("select * from {0} where formKey='{1}' and OperatorId='{2}'", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserId); DataTable customTable = SqlHelper.ExecuteDataTable(sqlValue); StringBuilder sBuilder = new StringBuilder(); bool isGroupIndex = false; bool isFilterInfo = false; bool isDisplayFiltering = false; string saveFieldName = string.Empty; //分组号 if (customTable.Columns.Contains("GroupIndex")) { isGroupIndex = true; saveFieldName = ",GroupIndex"; } //列筛选条件 if (customTable.Columns.Contains("FilterInfo")) { isFilterInfo = true; saveFieldName += ",FilterInfo"; } //是否显示筛选行 if (BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "DisplayFiltering")) { isDisplayFiltering = true; saveFieldName += ",DisplayFiltering"; } foreach (GridColumn col in gridView.Columns) { string fieldValue = string.Empty; string updateField = string.Empty; if (isGroupIndex) { fieldValue = ",'" + col.GroupIndex + "'"; updateField = string.Format(" ,GroupIndex='{0}' ", col.GroupIndex); } if (isFilterInfo) { fieldValue += ",'" + col.FilterInfo.FilterString.Replace("'", "''") + "'"; updateField += string.Format(" ,FilterInfo='{0}' ", col.FilterInfo.FilterString.Replace("'", "''")); } if (isDisplayFiltering) { fieldValue += gridView.OptionsView.ShowAutoFilterRow ? ",'1'" : ",'0'"; updateField += gridView.OptionsView.ShowAutoFilterRow ? " ,DisplayFiltering='1' " : " ,DisplayFiltering='0' "; } DataRow a = customTable.Rows.Cast().FirstOrDefault(x => col.Name.Equals(x["fieldName"] + "", StringComparison.OrdinalIgnoreCase)); string tempSql = a == null ? string.Format(@"insert into {8}(formkey,fieldname,username,orderid,isvisible,operatorid,operatorName,operatedate,fieldWidth,IfFixColumn {10}) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',getdate(),'{7}','{9}' {11});", key, col.FieldName, col.Caption.Replace("'", "''"), col.VisibleIndex, Convert.ToInt32(col.Visible), ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, col.Width, ResourceKeys.SettingTableName, col.Fixed == DevExpress.XtraGrid.Columns.FixedStyle.Left, saveFieldName, fieldValue) : string.Format(@"update {6} set orderid='{0}',fieldWidth='{1}',isvisible={2},IfFixColumn='{7}' {8} where formkey='{3}' and fieldname='{4}' and operatorid='{5}';", col.VisibleIndex, col.Width, Convert.ToInt32(col.Visible), key, col.FieldName, ERPInfo.Instance.UserId, ResourceKeys.SettingTableName, col.Fixed == DevExpress.XtraGrid.Columns.FixedStyle.Left, updateField); sBuilder.Append(tempSql); } return BaseImpl.ExecSqlValue(sBuilder.ToString()) > 0; } /// /// 说明:更新树表格个性列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// true if XXXX, false otherwise. public static bool UpdateCustomColumnToDatabase(this TreeList gridView, string key) { if (string.IsNullOrEmpty(key)) return false; if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "IfFixColumn")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } StringBuilder sBuilder = new StringBuilder(); foreach (TreeListColumn col in gridView.Columns) { string tempSql = string.Format(@"update {6} set orderid='{0}',fieldWidth='{1}',isvisible={2},IfFixColumn='{7}' where formkey='{3}' and fieldname='{4}' and operatorid='{5}';", col.VisibleIndex, col.Width, Convert.ToInt32(col.Visible), key, col.FieldName, ERPInfo.Instance.UserId, ResourceKeys.SettingTableName, col.Fixed == DevExpress.XtraTreeList.Columns.FixedStyle.Left); sBuilder.Append(tempSql); } return BaseImpl.ExecSqlValue(sBuilder.ToString()) > 0; } /// /// 说明:重置个性列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// 新列数据 /// true if XXXX, false otherwise. public static bool ResetCustomColumnToDatabase(this GridView gridView, string key) { if (string.IsNullOrEmpty(key)) return false; try { string sqlValue = string.Format("delete {0} where formKey='{1}' and operatorid='{2}'", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserId); BaseImpl.ExecSqlValue(sqlValue); return true; } catch (Exception) { return false; } } /// /// 说明:重置树表格个性列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// 新列数据 /// true if XXXX, false otherwise. public static bool ResetCustomColumnToDatabase(this TreeList gridView, string key) { if (string.IsNullOrEmpty(key)) return false; try { string sqlValue = string.Format("delete {0} where formKey='{1}' and operatorid='{2}'", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserId); BaseImpl.ExecSqlValue(sqlValue); return true; } catch (Exception) { return false; } } /// /// 说明:通过数据库获取个性配置列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// DataTable. public static DataTable GetCustomColumnByDatabase(this GridView gridView, string key) { try { // 读取普通用户读取个人配置,没有则读取管理员配置,管理未配置则读取系统默认.逐级上报读取方式. string sqlValue = string.Format("select * from {0} where formKey='{1}' and operatorid='{2}' order by orderid ", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserId); DataTable table = BaseImpl.GetDataTableResult(sqlValue); //if (table == null || table.Rows.Count == 0) //{ // sqlValue = string.Format("select * from {0} where formKey='{1}' and operatorid='{2}'", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserManager); // table = BaseImpl.GetDataTableResult(sqlValue); //} return table; } catch (Exception) { } return null; } /// /// 说明:通过数据库获取树表格个性配置列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The key. /// DataTable. public static DataTable GetCustomColumnByDatabase(this TreeList gridView, string key) { try { if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add IfFixColumn bit"); } // 读取普通用户读取个人配置,没有则读取管理员配置,管理未配置则读取系统默认.逐级上报读取方式. string sqlValue = string.Format("select * from {0} where formKey='{1}' and operatorid='{2}' order by orderid ", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserId); DataTable table = BaseImpl.GetDataTableResult(sqlValue); //if (table == null || table.Rows.Count == 0) //{ // sqlValue = string.Format("select * from {0} where formKey='{1}' and operatorid='{2}'", ResourceKeys.SettingTableName, key, ERPInfo.Instance.UserManager); // table = BaseImpl.GetDataTableResult(sqlValue); //} return table; } catch (Exception) { } return null; } /// /// 说明:清除列排序 /// 创建人:龚宇超 /// 创建日期:2017-11-30 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The column. /// GridColumn. public static BandedGridColumn ClearSort(this BandedGridColumn column) { column.SortOrder = DevExpress.Data.ColumnSortOrder.None; return column; } /// /// 说明:清除列排序 /// 创建人:龚宇超 /// 创建日期:2017-11-30 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The column. /// GridColumn. public static GridColumn ClearSort(this GridColumn column) { column.SortOrder = DevExpress.Data.ColumnSortOrder.None; return column; } /// /// 说明:清除所有列排序 /// 创建人:龚宇超 /// 创建日期:2017-11-30 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The columns. /// GridColumnCollection. public static GridColumnCollection ClearAllSort(this GridColumnCollection columns) { foreach (GridColumn item in columns) { item.ClearSort(); } return columns; } /// /// 说明:清除所有列排序 /// 创建人:龚宇超 /// 创建日期:2017-11-30 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The columns. /// GridColumnCollection. public static BandedGridColumnCollection ClearAllSort(this BandedGridColumnCollection columns) { foreach (BandedGridColumn item in columns) { item.ClearSort(); } return columns; } /// /// 说明:提交当前行数据 /// 创建人:龚宇超 /// 创建日期:2018-01-02 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. public static void PostFocusRow(this GridView gridView) { gridView.CloseEditor(); gridView.PostEditor(); gridView.UpdateCurrentRow(); } /// /// 说明:设置GridView选中行 /// 创建人:龚宇超 /// 创建日期:2017-12-05 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The handle. public static void SelectRowHandler(this GridView gridView, int handle) { if (gridView.OptionsSelection.MultiSelect == true && gridView.OptionsSelection.EnableAppearanceFocusedCell == false && gridView.OptionsSelection.MultiSelectMode == GridMultiSelectMode.CheckBoxRowSelect) { if (handle != 0) { gridView.ClearSelection(); gridView.FocusedRowHandle = handle; gridView.SelectRow(handle); } } else { if (handle < 0) handle = 0; gridView.ClearSelection(); gridView.FocusedRowHandle = handle; gridView.SelectRow(handle); } } /// /// 说明:设置表格右键菜单 /// 创建人:龚宇超 /// 创建日期:2017-12-19 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The table. /// The handler. public static void SetGridRightMenus(this GridControlEx gridControl, DataTable table, DynamicModel model, EventHandler handler = null, MyControl control = null, ContextMenuStrip menu = null) { BaseRightMenu rightMenu = new GridViewMenuStrip(); gridControl.gridViewRightMenu = rightMenu; rightMenu.InitRightMenus(gridControl, table, model, control, menu); rightMenu.SetRightCallback(handler); } /// /// 说明:设置表格右键菜单 /// 创建人:龚宇超 /// 创建日期:2017-12-19 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The table. /// The handler. public static void SetGridRightMenus(this TreeGridControlEx gridControl, DataTable table, DynamicModel model, EventHandler handler = null, MyControl control = null, ContextMenuStrip menu = null) { TreeGridViewMenuStrip rightMenu = new TreeGridViewMenuStrip(); gridControl.gridViewRightMenu = rightMenu; rightMenu.InitRightMenus(gridControl, table, model, control, menu); rightMenu.SetRightCallback(handler); } /// /// 说明:设置表格右键菜单 /// 创建人:龚宇超 /// 创建日期:2017-12-19 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid view. /// The table. /// The handler. public static void SetGridRightMenus(this BandedGridControlEx gridControl, DataTable table, DynamicModel model, EventHandler handler = null, MyControl control = null, ContextMenuStrip menu = null) { BandedGridMenuStrip rightMenu = new BandedGridMenuStrip(); gridControl.gridViewRightMenu = rightMenu; rightMenu.InitRightMenus(gridControl, table, model, control, menu); rightMenu.SetRightCallback(handler); } /// /// 说明:设置图标右键菜单 /// 创建人:龚宇超 /// 创建日期:2018-01-29 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The chart control. /// The table. /// The model. /// The handler. public static void SetChartRightMenus(this ChartControlEx chartControl, DataTable table, DynamicModel model, EventHandler handler = null) { BaseRightMenu rightMenu = new ChartViewMenuStrip(); rightMenu.InitRightMenus(chartControl, table, model, null, null); rightMenu.SetRightCallback(handler); } /// /// 说明:表格导出文件 /// 创建人:王一帆 /// 创建日期:2022-05-19 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. public static void ToExcel(this BandedGridControlEx bandedGridControlEx, string menuName, bool ismerger = false) { if (bandedGridControlEx == null) return; SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "导出"; String suffix = SystemInfo.Instance.IsXlsxFirst ? ".xlsx" : ".xls"; dialog.FileName = menuName + DateTime.Now.ToString(SystemInfo.Instance.ExportFileDateFormat) + suffix; dialog.Filter = SystemInfo.Instance.IsXlsxFirst ? "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html" : "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { WaitForm.ShowForm("导出中,请稍后..."); try { FrmExport export = new FrmExport(); DevExpress.XtraPrinting.XlsxExportOptionsEx op = new DevExpress.XtraPrinting.XlsxExportOptionsEx(); op.ExportType = DevExpress.Export.ExportType.WYSIWYG; DevExpress.XtraPrinting.XlsExportOptionsEx opxls = new DevExpress.XtraPrinting.XlsExportOptionsEx(); opxls.ExportType = DevExpress.Export.ExportType.WYSIWYG; BandedGridControlEx NewBandedGridControlEx = export.ReplaceBitColumn(bandedGridControlEx); BandedGridView gridView = NewBandedGridControlEx.GridView as BandedGridView; gridView.OptionsPrint.PrintHeader = true; gridView.OptionsPrint.AutoWidth = false; DataTable dataTable = gridView.GetGridViewFilteredAndSortedDataToDataTable();//获取数据表 int Rowcount = dataTable.Rows.Count;//获取execl表的大小 string fileExt = Path.GetExtension(dialog.FileName).ToLower(); switch (fileExt) { case ".xls": if (Rowcount > 65536) { MessageUtil.Show("超过excel最大的保存数量!"); return; } //|| Rowcount < 26000 gridView.ExportToXls(dialog.FileName, opxls); break; case ".xlsx": //|| Rowcount < 26000 gridView.ExportToXlsx(dialog.FileName, op); break; case ".pdf": gridView.ExportToPdf(dialog.FileName); break; case ".rtf": gridView.ExportToRtf(dialog.FileName); break; case ".html": gridView.ExportToHtml(dialog.FileName); break; } if (SystemInfo.Instance.ExportModuleName) { PanelControl panel = null; if (bandedGridControlEx.gridControl.Tag is PanelControl) panel = bandedGridControlEx.gridControl.Tag as PanelControl; SetModuleName(dialog.FileName, fileExt, gridView.Columns.Cast().Count(column => column.Visible), true, panel); } MessageUtil.Show(ResourceKeys.ExportSuccess); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("表格导出文件错误", ex); //MessageUtil.Show(ResourceKeys.ExportFault + ex); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { WaitForm.HideForm(); } } } /// /// 说明:表格导出文件 /// 创建人:龚宇超 /// 创建日期:2017-11-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. public static void ToExcel(this GridControl control, string menuName, bool ismerger = false, string CustomColumKey = "") { if (control == null) return; SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "导出"; String suffix = SystemInfo.Instance.IsXlsxFirst ? ".xlsx" : ".xls"; dialog.FileName = menuName + DateTime.Now.ToString(SystemInfo.Instance.ExportFileDateFormat) + suffix; dialog.Filter = SystemInfo.Instance.IsXlsxFirst ? "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html" : "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { WaitForm.ShowForm("导出中,请稍后..."); try { //获取设置的导出列 DataTable isExportTab = new DataTable(); if (!string.IsNullOrEmpty(CustomColumKey)) { try { string sqlstr = "select fieldName,userName from {0} where {1}='{2}' and isExport='1' and OperatorName='{3}'"; sqlstr = string.Format(sqlstr, ResourceKeys.SettingExportTableName, "formkey", CustomColumKey, ERPInfo.Instance.UserName); isExportTab = SqlHelper.ExecuteDataTable(sqlstr); } catch (Exception) { } } List ExportColumnsName = new List(); List NoExportColumnsName = new List(); foreach (GridColumn col in (control.FocusedView as GridView).Columns) { if (isExportTab != null && isExportTab.Rows.Count > 0 && isExportTab.Columns.Contains("fieldName")) { DataRow[] dataRows = isExportTab.Select(string.Format("fieldName='{0}'", col.FieldName)); if (dataRows != null && dataRows.Length > 0) { ExportColumnsName.Add(col.FieldName); } else { NoExportColumnsName.Add(col.FieldName); } } } FrmExport export = new FrmExport(); GridControl newControl = export.ReplaceBitColumn(control, NoExportColumnsName.Count() != 0); GridView gridView = newControl.FocusedView as GridView; //如果有导出列,则只导出设置的列,否则全部导出 if (ExportColumnsName.Count > 0) { foreach (string item in NoExportColumnsName) { GridColumn column = gridView.Columns.FirstOrDefault(x => x.FieldName.Equals(item)); if (column != null) gridView.Columns.Remove(column); } } if (SystemInfo.Instance.ExportClearItemSource) { foreach (GridColumn column in gridView.Columns)//取消表格列下拉控件 { if (column.ColumnEdit != null && column.ColumnEdit is DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit) { column.ColumnEdit = null; } } } gridView.OptionsPrint.AutoWidth = false; DataTable dataTable = gridView.GetGridViewFilteredAndSortedDataToDataTable();//获取数据表 int totalRowCount = dataTable.Rows.Count; int maxRowCount = 65536; if (ismerger) { (newControl.MainView as GridView).CellMerge += new CellMergeEventHandler(OnGridViewCellMerge); (newControl.MainView as GridView).OptionsView.AllowCellMerge = true; } CompositeLink link = export.ReplaceBitLink(newControl); //PrintableComponentLink linkPDF = new PrintableComponentLink(new PrintingSystem()); //linkPDF.Component = control; string fileExt = Path.GetExtension(dialog.FileName).ToLower(); // 创建导出选项 XlsExportOptions options = new XlsExportOptions(); // 设置导出时不包含筛选信息 //options.ExportFilterInfo = false; //if (fileExt.Equals(".pdf")) //{ // GridView mainGridView = newControl.MainView as GridView; // mainGridView.Appearance.Row.Font = new Font("黑体", 9); // mainGridView.Appearance.HeaderPanel.Font = new Font("黑体", 9); // foreach (GridColumn item in mainGridView.Columns) // { // item.AppearanceHeader.Font = new Font("黑体", 9); // item.AppearanceCell.Font = new Font("黑体", 9); // item.MinWidth = 200; // } //} switch (fileExt) { case ".xls": if (totalRowCount > maxRowCount) { MessageUtil.Show("超过excel最大的保存数量!"); return; } //maxRowCount = 1; if (gridView is BandedGridView) { link.ExportToXls(dialog.FileName); } else { newControl.ExportToXls(dialog.FileName); //control.ExportToXls(dialog.FileName); } break; case ".xlsx": newControl.ExportToXlsx(dialog.FileName); break; case ".pdf": //link.ExportToPdf(dialog.FileName); newControl.ExportToPdf(dialog.FileName); //newControl.PrintDialog(); //newControl.Print(); break; case ".rtf": link.ExportToRtf(dialog.FileName); break; case ".html": link.ExportToHtml(dialog.FileName); break; } if (SystemInfo.Instance.ExportModuleName) { PanelControl panel = null; if (control.Tag is PanelControl) panel = control.Tag as PanelControl; SetModuleName(dialog.FileName, fileExt, gridView.Columns.Cast().Count(column => column.Visible), false, panel); } MessageUtil.Show(ResourceKeys.ExportSuccess); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("表格导出文件错误", ex); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { WaitForm.HideForm(); } } } /// /// 说明:表格导出文件 /// 创建人:曹屹峰 /// 创建日期:2024-07-26 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. public static void ToTreeExcel(this TreeList control, string menuName, bool ismerger = false, string CustomColumKey = "") { if (control == null) return; SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "导出"; String suffix = SystemInfo.Instance.IsXlsxFirst ? ".xlsx" : ".xls"; dialog.FileName = menuName + DateTime.Now.ToString(SystemInfo.Instance.ExportFileDateFormat) + suffix; dialog.Filter = SystemInfo.Instance.IsXlsxFirst ? "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html" : "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { WaitForm.ShowForm("导出中,请稍后..."); FrmTreeExport export = new FrmTreeExport(); try { //获取设置的导出列 DataTable isExportTab = new DataTable(); if (!string.IsNullOrEmpty(CustomColumKey)) { try { string sqlstr = "select fieldName,userName from {0} where {1}='{2}' and isExport='1' and OperatorName='{3}'"; sqlstr = string.Format(sqlstr, ResourceKeys.SettingExportTableName, "formkey", CustomColumKey, ERPInfo.Instance.UserName); isExportTab = SqlHelper.ExecuteDataTable(sqlstr); } catch (Exception) { } } List ExportColumnsName = new List(); List NoExportColumnsName = new List(); foreach (TreeListColumn col in control.Columns) { if (isExportTab != null && isExportTab.Rows.Count > 0 && isExportTab.Columns.Contains("fieldName")) { DataRow[] dataRows = isExportTab.Select(string.Format("fieldName='{0}'", col.FieldName)); if (dataRows != null && dataRows.Length > 0) { ExportColumnsName.Add(col.FieldName); } else { NoExportColumnsName.Add(col.FieldName); } } } TreeList newControl = export.ReplaceBitColumn(control, NoExportColumnsName.Count() != 0); newControl.ExpandAll(); // 设置透明后展示控件(展示后导出才有数据,否则为空文件) export.Opacity = 0; export.Show(); export.Visible = false; //如果有导出列,则只导出设置的列,否则全部导出 if (ExportColumnsName.Count > 0) { foreach (string item in NoExportColumnsName) { TreeListColumn column = newControl.Columns.FirstOrDefault(x => x.FieldName.Equals(item)); if (column != null) newControl.Columns.Remove(column); } } if (SystemInfo.Instance.ExportClearItemSource) { foreach (TreeListColumn column in newControl.Columns)//取消表格列下拉控件 { if (column.ColumnEdit != null && column.ColumnEdit is DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit) { column.ColumnEdit = null; } } } newControl.OptionsPrint.AutoWidth = false; DataTable dataTable = newControl.DataSource as DataTable;//获取数据表 int totalRowCount = dataTable.Rows.Count; int maxRowCount = 65536; CompositeLink link = export.ReplaceBitLink(newControl); string fileExt = Path.GetExtension(dialog.FileName).ToLower(); switch (fileExt) { case ".xls": if (totalRowCount > maxRowCount) { MessageUtil.Show("超过excel最大的保存数量!"); return; } newControl.ExportToXls(dialog.FileName); break; case ".xlsx": newControl.ExportToXlsx(dialog.FileName); break; case ".pdf": link.ExportToPdf(dialog.FileName); break; case ".rtf": link.ExportToRtf(dialog.FileName); break; case ".html": link.ExportToHtml(dialog.FileName); break; } MessageUtil.Show(ResourceKeys.ExportSuccess); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("表格导出文件错误", ex); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { export.Dispose(); WaitForm.HideForm(); } } } public static bool AllToExcel(this GridControl control, string menuName, bool firstLoad) { if (control == null) return false; DialogResult result = new DialogResult(); if (firstLoad) { exportAddress = null; suffix = null; SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "所有模块导出"; String TheSuffix = SystemInfo.Instance.IsXlsxFirst ? ".xlsx" : ".xls"; dialog.FileName = menuName + DateTime.Now.ToString(SystemInfo.Instance.ExportFileDateFormat) + TheSuffix; dialog.Filter = SystemInfo.Instance.IsXlsxFirst ? "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html" : "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html"; result = dialog.ShowDialog(); string[] FileName = dialog.FileName.Split('\\'); for (int i = 0; i < FileName.Length - 1; i++) { exportAddress += FileName[i].ToString() + "\\"; } suffix = Path.GetExtension(dialog.FileName).ToLower(); } if (result == DialogResult.OK || !firstLoad) { WaitForm.ShowForm("导出中,请稍后..."); try { FrmExport export = new FrmExport(); GridControl newControl = export.ReplaceBitColumn(control); GridView gridView = newControl.FocusedView as GridView; gridView.OptionsPrint.AutoWidth = false; int Rowcount = control.DataSourceTable().Rows.Count;//获取execl表的大小 CompositeLink link = export.ReplaceBitLink(newControl); switch (suffix) { case ".xls": //|| Rowcount < 26000 if (Rowcount > 65536) { MessageUtil.Show("超过excel最大的保存数量!"); return false; } if (gridView is BandedGridView) { link.ExportToXls(exportAddress + menuName + suffix); } else { newControl.ExportToXls(exportAddress + menuName + suffix); } break; case ".xlsx": link.ExportToXlsx(exportAddress + menuName + suffix); break; case ".pdf": link.ExportToPdf(exportAddress + menuName + suffix); break; case ".rtf": link.ExportToRtf(exportAddress + menuName + suffix); break; case ".html": link.ExportToHtml(exportAddress + menuName + suffix); break; } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("表格导出文件错误", ex); //MessageUtil.Show(ResourceKeys.ExportFault + ex); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { WaitForm.HideForm(); } } else { return false; } return true; } /// /// 说明:导出Excel /// 创建人:龚宇超 /// 创建日期:2019-10-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The data table. public static void ToExcelTreeList(this TreeList control, string menuName) { if (control == null) return; SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "导出"; dialog.FileName = menuName + DateTime.Now.ToString(SystemInfo.Instance.ExportFileDateFormat) + ".xls"; dialog.Filter = "Excel文件(*.xls)|*.xls|Excel2007|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { WaitForm.ShowForm("导出中,请稍后..."); try { FrmExport export = new FrmExport(); // CompositeLink link = export.ReplaceBitLink(control); if (dialog.FilterIndex == 1) { control.ExportToXls(dialog.FileName); } if (dialog.FilterIndex == 2) { control.ExportToXlsx(dialog.FileName); } if (dialog.FilterIndex == 3) { control.ExportToPdf(dialog.FileName); } if (dialog.FilterIndex == 4) { control.ExportToRtf(dialog.FileName); } if (dialog.FilterIndex == 5) { control.ExportToHtml(dialog.FileName); } MessageUtil.Show(ResourceKeys.ExportSuccess); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("表格导出文件错误", ex); //MessageUtil.Show(ResourceKeys.ExportFault); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { WaitForm.HideForm(); } } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. public static void ToExcelTemplate(this GridControl control, string menuName) { if (control == null) return; SaveFileDialog dialog = new SaveFileDialog(); dialog.Title = "导出"; dialog.FileName = menuName + DateTime.Now.ToString(SystemInfo.Instance.ExportFileDateFormat) + ".xls"; dialog.Filter = "Excel文件(*.xls)|*.xls|Excel2007|*.xlsx|PDF文件|*.PDF|RTF文件|*.RTF|HTML文件|*.html"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { WaitForm.ShowForm("导出中,请稍后..."); try { if (dialog.FilterIndex == 1) { control.ExportToXls(dialog.FileName); } if (dialog.FilterIndex == 2) { control.ExportToXlsx(dialog.FileName); } if (dialog.FilterIndex == 3) { control.ExportToPdf(dialog.FileName); } if (dialog.FilterIndex == 4) { control.ExportToRtf(dialog.FileName); } if (dialog.FilterIndex == 5) { control.ExportToHtml(dialog.FileName); } MessageUtil.Show(ResourceKeys.ExportSuccess); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("表格模板导出文件错误", ex); //MessageUtil.Show(ResourceKeys.ExportFault); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } finally { WaitForm.HideForm(); } } } /// /// 说明:获取GridView过滤或排序后的数据集 /// 创建人:龚宇超 /// 创建日期:2019-04-11 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The view. /// DataTable. public static DataTable GetGridViewFilteredAndSortedDataToDataTable(this DevExpress.XtraGrid.Views.Grid.GridView view) { DataTable _dt = view.GridControl.DataSourceTable(); if (_dt == null) return null; DataTable dt = _dt.Clone(); for (int i = 0; i < view.RowCount; i++) { if (view.IsGroupRow(i)) continue; var dr = view.GetDataRow(i); if (dr == null) continue; dt.Rows.Add(dr.ItemArray); } return dt; } /// /// 获取排序和筛选后的数据源 /// /// /// public static DataTable GetFilteredAndSortedDataTable(this GridView view) { DataTable dataSource = view.GridControl.DataSourceTable(); string filterCondition = CriteriaToWhereClauseHelper.GetDataSetWhere(view.ActiveFilterCriteria); string pattern = @"len\(\[([^\]]+)\]\)"; // 使用正则表达式替换 filterCondition = Regex.Replace(filterCondition, pattern, match => { string field = match.Groups[1].Value; return $"len(Convert([{field}], 'System.String'))"; }); string sortCondition = ""; foreach (GridColumnSortInfo sortInfo in view.SortInfo) { if (sortCondition != "") { sortCondition += ", "; } string sortOrder = sortInfo.SortOrder == ColumnSortOrder.Ascending ? "ASC" : "DESC"; sortCondition += $"{sortInfo.Column.FieldName} {sortOrder}"; } DataView dataView = new DataView(dataSource); dataView.RowFilter = filterCondition; dataView.Sort = sortCondition; return dataView.ToTable(); } /// /// 说明:获取GridControl的DataTable /// 创建人:龚宇超 /// 创建日期:2017-12-05 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. /// DataTable. public static DataTable DataSourceTable(this GridControl control) { return control == null || control.DataSource == null ? new DataTable() : control.DataSource as DataTable; } /// /// 说明:获取导入到下拉框里的显示值 /// 创建人:王一帆 /// 创建日期:2020-04-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0.0.3 /// /// The control. /// DataTable. public static string GetValueByImportText(DataRow row, string fieldName, string text, bool isBillImport = false) { string value = text; foreach (GridColumnModel model in ValueGridColumnTable.Keys) { if (model.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase)) { string selWhere = "1=1"; DataTable table = ValueGridColumnTable[model]; if (table != null && table.Rows.Count > 0) { DataRow rowItemValue = table.Rows.Cast().FirstOrDefault(x => x[model.TextMember] + "" == text); DataRow rowItemText = table.Rows.Cast().FirstOrDefault(x => x[model.ValueMember] + "" == text); //value = rowItemValue != null ? rowItemValue[isBillImport ? model.ValueMember : model.TextMember] + "" : rowItemText != null ? rowItemText[isBillImport ? model.ValueMember : model.TextMember] + "" : ""; value = rowItemValue != null ? rowItemValue[model.ValueMember] + "" : rowItemText != null ? rowItemText[model.ValueMember] + "" : ""; } else value = ""; } } return value; } /// /// 说明:导入到表格中 /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0.0.3 /// /// The col fields. public static DataTable ToExcelDataTable(this GridView gridView, string fileName, string colFields, bool isDirectImport = false, bool isBillImport = false) { DataTable table = new DataTable(); int index = gridView is BandedGridView ? 1 : 0; isBillImport = index == 1 ? true : isBillImport; string fileExt = Path.GetExtension(fileName).ToLower(); int CurrentRow = 0;//当前行数 int CurrentColumn = 0;//当前列数 string columnName = string.Empty;//当前列名 bool ToAssignment = false;//是否在给新表赋值 try { ISheet sheet = ExcelHelper.GetSheet(fileName); IRow BandheaderRow = sheet.GetRow(0); bool isMerged = false; foreach (ICell item in BandheaderRow.Cells) { if (item.IsMergedCell) { isMerged = true; break; } } if (!isMerged) { index = 0; } IRow headerRow = sheet.GetRow(index); BandedGridView newBandGrid = null; string bandTitel = string.Empty; ColumnList.Clear(); ColumnNameList.Clear(); // 添加列 for (int i = 0; i < headerRow.LastCellNum; i++) { ICell cell = headerRow.GetCell(i); if (cell == null) continue; if (index != 1) { GridColumn col = gridView.Columns.OfType().FirstOrDefault(x => Regex.Replace(x.Caption, @"\s", "") == Regex.Replace(cell.ToString(), @"\s", "")); if (col != null) { if (!table.Columns.Contains(col.FieldName)) { table.Columns.Add(col.FieldName, col.ColumnType); ColumnList.Add(col.Tag as GridColumnModel); ColumnNameList.Add(col.FieldName); } } else { MessageUtil.Show("未找到列->" + cell + ""); } } else { newBandGrid = gridView as BandedGridView; ICell Bandcell = BandheaderRow.GetCell(i); if (!bandTitel.Equals(Bandcell + "") && !string.IsNullOrEmpty(Bandcell + "")) bandTitel = Bandcell + ""; BandedGridColumn col2 = newBandGrid.Columns.OfType().FirstOrDefault(x => Regex.Replace(x.OwnerBand + x.Caption, @"\s", "") == Regex.Replace(bandTitel + cell.ToString(), @"\s", "")); if (col2 != null) { if (!table.Columns.Contains(col2.FieldName)) { table.Columns.Add(col2.FieldName, col2.ColumnType); ColumnList.Add(col2.Tag as GridColumnModel); ColumnNameList.Add(col2.FieldName); } } else { MessageUtil.Show("未找到列->" + bandTitel + " " + cell + ""); } } } InitializeValueGrid(gridView); if (colFields.IndexOf("import_errormsg") != -1 && !table.Columns.Contains("import_errormsg")) table.Columns.Add("import_errormsg"); if (colFields.IndexOf("lskjimport_errorFlag") != -1 && !table.Columns.Contains("lskjimport_errorFlag")) table.Columns.Add("lskjimport_errorFlag"); bool AutoImportCal = SystemInfo.Instance.AutoImportCal;//是否执行 关联和计算公式 //bool ImportDefaultValue= SystemInfo.Instance.ImportDefaultValue;//是否为空单元格添加默认值 //bool isImportRows = true;//是否是导入行(如果是合计行就不触发默认值) // 添加行 for (int i = sheet.FirstRowNum + 1 + index; i <= sheet.LastRowNum; i++) { ToAssignment = true; CurrentRow = i; GridColumn col = new GridColumn(); IRow row = sheet.GetRow(i); if (row == null) continue; bandTitel = string.Empty; DataRow dataRow = table.NewRow(); //if (i == sheet.LastRowNum && fileExt == ".xlsx") break; //isImportRows = true; for (int j = row.FirstCellNum; j < headerRow.LastCellNum; j++) { CurrentColumn = j; ICell cell = row.GetCell(j); ICell headcell = headerRow.GetCell(j); ICell Bandcell = BandheaderRow.GetCell(j); if (headcell == null && Bandcell == null) continue; //cell.CellStyle.Indention 获取单元格的缩进 columnName = headcell.StringCellValue; if (!bandTitel.Equals(Bandcell + "") && !string.IsNullOrEmpty(Bandcell + "")) bandTitel = Bandcell + ""; col = index != 1 ? gridView.Columns.OfType().FirstOrDefault(x => Regex.Replace(x.Caption, @"\s", "") == Regex.Replace(headcell.ToString(), @"\s", "")) : newBandGrid.Columns.OfType().FirstOrDefault(x => Regex.Replace(x.OwnerBand + x.Caption, @"\s", "") == Regex.Replace(bandTitel + headcell.ToString(), @"\s", "")); if (col == null) continue; GridColumnModel model = col.Tag as GridColumnModel; if (cell != null) { if (cell.CellType == CellType.Blank) { //isImportRows = false; continue; } if (cell.CellType == CellType.Formula) { //isImportRows = false; // dataRow[col.FieldName] = cell.StringCellValue; continue; } if (cell.CellType == CellType.Numeric && (cell.NumericCellValue + "").StartsWith("-")) { dataRow[col.FieldName] = cell.NumericCellValue; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } else { if (cell.CellType == CellType.Numeric) { //GridColumnModel model = col.Tag as GridColumnModel; if (model != null && isDirectImport && (model.FieldType == ControlType.LabDate || model.FieldType == ControlType.LabDateTime || model.FieldType == ControlType.LabDateTimeShort || model.FieldType == ControlType.LabTime || model.FieldType == ControlType.LabShortTime)) { string fieldValue = ToDateTimeValue(cell.NumericCellValue + ""); if (fieldValue != "") { dataRow[col.FieldName] = Convert.ToDateTime(fieldValue); if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { dataRow[col.FieldName] = cell.NumericCellValue; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { //GridColumnModel model = col.Tag as GridColumnModel; if (model != null && isDirectImport && (model.FieldType == ControlType.LabTreeType || model.FieldType == ControlType.LabComboxValue || model.FieldType == ControlType.LabComboxValueParam || model.FieldType == ControlType.LabAutoCompleteValue || model.FieldType == ControlType.LabAutoCompleteValueParam || model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabTreeLookValue || model.FieldType == ControlType.LabCheckBox || model.FieldType == ControlType.LabAutoGridValue || model.FieldType == ControlType.LabAutoGridValueParam || model.FieldType == ControlType.LabSelectReturnId )) { bool isEmpty = model.CanNull; string fieldValue = GetValueByImportText(dataRow, col.FieldName, cell + "", isBillImport); if ((model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam) && cell.ToString().Contains(",")) { string[] cellText = cell.ToString().Split(','); foreach (string cellValue in cellText) { fieldValue += GetValueByImportText(dataRow, col.FieldName, cellValue, isBillImport) + ','; } fieldValue = fieldValue.TrimEnd(','); } if (string.IsNullOrEmpty(fieldValue)) { if (isEmpty) { MessageUtil.Show("该列不允许为空->" + col.Caption + ""); } else { GridColumn column = gridView.Columns[col.FieldName]; if (column.ColumnType.Name.ToLower().IndexOf("int") >= 0) if (column.ColumnType.Name.ToLower() == "string") dataRow[col.FieldName] = ""; if (column.ColumnType.Name.ToLower().IndexOf("char") >= 0) dataRow[col.FieldName] = ""; if (column.ColumnType.Name.ToLower().IndexOf("int") >= 0) dataRow[col.FieldName] = 0; if (column.ColumnType.Name.ToLower() == "decimal") dataRow[col.FieldName] = 0; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { if (model.FieldType == ControlType.LabCheckBox && int.TryParse(fieldValue, out int labCheckBox)) { dataRow[col.FieldName] = labCheckBox; } else { dataRow[col.FieldName] = fieldValue; } if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { IRichTextString richTextString = (IRichTextString)cell.RichStringCellValue; if (fileExt == ".xlsx") { cell.SetCellValue(richTextString); } else if (fileExt == ".xls") { string cellValue = string.Empty; for (int m = 0; m < richTextString.Length; m++) { //string aaa = richTextString.String.Substring(m , 1); //short aaa = richTextString.GetFontAtIndex(m); IFont font = sheet.Workbook.GetFontAt(richTextString.GetFontAtIndex(m));//richTextString.GetFontAtIndex(m) string str = string.Empty; string code = richTextString.ToString().Substring(m, 1); switch (font.TypeOffset) { case FontSuperScript.Sub: str = ChemistryHelper.GetSubChar(code); break; case FontSuperScript.Super: str = ChemistryHelper.GetSuperChar(code); break; default: str = code; break; } cellValue = cellValue + str; } cell.SetCellValue(cellValue); } dataRow[col.FieldName] = cell + ""; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } } } //if (ImportDefaultValue&& isImportRows && string.IsNullOrEmpty(dataRow[col.FieldName] + "") && !string.IsNullOrEmpty(model.DefaultValue)) //{ // dataRow[col.FieldName] = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(dataRow, model.DefaultValue)); // if (!string.IsNullOrEmpty(model.UnionFields)) // { // SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); // } //} } table.Rows.Add(dataRow); } ToAssignment = false; } catch (InvalidOperationException ex) { if (ToAssignment && (CurrentRow != 0 || CurrentColumn != 0)) { string value = string.Format("第{0}行,第{1}列 {2},值出现异常", CurrentRow, CurrentColumn + 1, columnName); MessageUtil.Show(value); } else { MessageUtil.Show(ResourceKeys.DeleteLastTotalRow); } } catch (IOException exe) { //string Message = ErrorMessage.PromptErrorMessage(exe); //MessageUtil.Show(Message, exe.Message); MessageUtil.Show(string.Format(ResourceKeys.UseingFile, Path.GetFileName(fileName))); } catch (Exception ex) { //MessageUtil.Show(ResourceKeys.ImportFault + ex.Message); LogUtil.WriteError("读取excel出错!", ex); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } return table.TrimEmptyRows(); } /// /// 说明:导入到表格中 /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0.0.3 /// /// The col fields. public static DataTable ToExcelTreeDataTable(this TreeList treeList, string fileName, string colFields, bool isDirectImport = false, bool isBillImport = false) { DataTable table = new DataTable(); isBillImport = isBillImport; string fileExt = Path.GetExtension(fileName).ToLower(); int CurrentRow = 0;//当前行数 int CurrentColumn = 0;//当前列数 string columnName = string.Empty;//当前列名 bool ToAssignment = false;//是否在给新表赋值 try { ISheet sheet = ExcelHelper.GetSheet(fileName); IRow BandheaderRow = sheet.GetRow(0); bool isMerged = false; foreach (ICell item in BandheaderRow.Cells) { if (item.IsMergedCell) { isMerged = true; break; } } IRow headerRow = sheet.GetRow(0); BandedGridView newBandGrid = null; string bandTitel = string.Empty; ColumnList.Clear(); ColumnNameList.Clear(); // 添加列 for (int i = 0; i < headerRow.LastCellNum; i++) { ICell cell = headerRow.GetCell(i); TreeListColumn col = treeList.Columns.OfType().FirstOrDefault(x => Regex.Replace(x.Caption, @"\s", "") == Regex.Replace(cell.ToString(), @"\s", "")); if (col != null) { if (!table.Columns.Contains(col.FieldName)) { table.Columns.Add(col.FieldName, col.ColumnType); ColumnList.Add(col.Tag as GridColumnModel); ColumnNameList.Add(col.FieldName); } } else { MessageUtil.Show("未找到列->" + cell + ""); } } InitializeValueGrid(treeList); if (colFields.IndexOf("import_errormsg") != -1 && !table.Columns.Contains("import_errormsg")) table.Columns.Add("import_errormsg"); if (colFields.IndexOf("lskjimport_errorFlag") != -1 && !table.Columns.Contains("lskjimport_errorFlag")) table.Columns.Add("lskjimport_errorFlag"); bool AutoImportCal = SystemInfo.Instance.AutoImportCal;//是否执行 计算公式 //bool ImportDefaultValue= SystemInfo.Instance.ImportDefaultValue;//是否为空单元格添加默认值 //bool isImportRows = true;//是否是导入行(如果是合计行就不触发默认值) // 添加行 for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++) { ToAssignment = true; CurrentRow = i; TreeListColumn col = new TreeListColumn(); IRow row = sheet.GetRow(i); if (row == null) continue; bandTitel = string.Empty; DataRow dataRow = table.NewRow(); //if (i == sheet.LastRowNum && fileExt == ".xlsx") break; //isImportRows = true; for (int j = row.FirstCellNum; j < headerRow.LastCellNum; j++) { CurrentColumn = j; ICell cell = row.GetCell(j); ICell headcell = headerRow.GetCell(j); ICell Bandcell = BandheaderRow.GetCell(j); //cell.CellStyle.Indention 获取单元格的缩进 columnName = headcell.StringCellValue; if (!bandTitel.Equals(Bandcell + "") && !string.IsNullOrEmpty(Bandcell + "")) bandTitel = Bandcell + ""; col = treeList.Columns.OfType().FirstOrDefault(x => Regex.Replace(x.Caption, @"\s", "") == Regex.Replace(headcell.ToString(), @"\s", "")); if (col == null) continue; GridColumnModel model = col.Tag as GridColumnModel; if (cell != null) { if (cell.CellType == CellType.Blank) { //isImportRows = false; continue; } if (cell.CellType == CellType.Formula) { //isImportRows = false; continue; } if (cell.CellType == CellType.Numeric && (cell.NumericCellValue + "").StartsWith("-")) { dataRow[col.FieldName] = cell.NumericCellValue; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } else { if (cell.CellType == CellType.Numeric) { //GridColumnModel model = col.Tag as GridColumnModel; if (model != null && isDirectImport && (model.FieldType == ControlType.LabDate || model.FieldType == ControlType.LabDateTime || model.FieldType == ControlType.LabDateTimeShort || model.FieldType == ControlType.LabTime || model.FieldType == ControlType.LabShortTime)) { string fieldValue = ToDateTimeValue(cell.NumericCellValue + ""); if (fieldValue != "") { dataRow[col.FieldName] = Convert.ToDateTime(fieldValue); if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { dataRow[col.FieldName] = cell.NumericCellValue; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { //GridColumnModel model = col.Tag as GridColumnModel; if (model != null && isDirectImport && (model.FieldType == ControlType.LabTreeType || model.FieldType == ControlType.LabComboxValue || model.FieldType == ControlType.LabComboxValueParam || model.FieldType == ControlType.LabAutoCompleteValue || model.FieldType == ControlType.LabAutoCompleteValueParam || model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabTreeLookValue || model.FieldType == ControlType.LabCheckBox || model.FieldType == ControlType.LabAutoGridValue || model.FieldType == ControlType.LabAutoGridValueParam || model.FieldType == ControlType.LabSelectReturnId )) { bool isEmpty = model.CanNull; string fieldValue = GetValueByImportText(dataRow, col.FieldName, cell + "", isBillImport); if ((model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam) && cell.ToString().Contains(",")) { string[] cellText = cell.ToString().Split(','); foreach (string cellValue in cellText) { fieldValue += GetValueByImportText(dataRow, col.FieldName, cellValue, isBillImport) + ','; } fieldValue = fieldValue.TrimEnd(','); } if (string.IsNullOrEmpty(fieldValue)) { if (isEmpty) { MessageUtil.Show("该列不允许为空->" + col.Caption + ""); } else { TreeListColumn column = treeList.Columns[col.FieldName]; if (column.ColumnType.Name.ToLower().IndexOf("int") >= 0) if (column.ColumnType.Name.ToLower() == "string") dataRow[col.FieldName] = ""; if (column.ColumnType.Name.ToLower().IndexOf("char") >= 0) dataRow[col.FieldName] = ""; if (column.ColumnType.Name.ToLower().IndexOf("int") >= 0) dataRow[col.FieldName] = 0; if (column.ColumnType.Name.ToLower() == "decimal") dataRow[col.FieldName] = 0; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { if (model.FieldType == ControlType.LabCheckBox && int.TryParse(fieldValue, out int labCheckBox)) { dataRow[col.FieldName] = labCheckBox; } else { dataRow[col.FieldName] = fieldValue; } if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } else { IRichTextString richTextString = (IRichTextString)cell.RichStringCellValue; if (fileExt == ".xlsx") { cell.SetCellValue(richTextString); } else if (fileExt == ".xls") { string cellValue = string.Empty; for (int m = 0; m < richTextString.Length; m++) { //string aaa = richTextString.String.Substring(m , 1); //short aaa = richTextString.GetFontAtIndex(m); IFont font = sheet.Workbook.GetFontAt(richTextString.GetFontAtIndex(m));//richTextString.GetFontAtIndex(m) string str = string.Empty; string code = richTextString.ToString().Substring(m, 1); switch (font.TypeOffset) { case FontSuperScript.Sub: str = ChemistryHelper.GetSubChar(code); break; case FontSuperScript.Super: str = ChemistryHelper.GetSuperChar(code); break; default: str = code; break; } cellValue = cellValue + str; } cell.SetCellValue(cellValue); } dataRow[col.FieldName] = cell + ""; if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } } } //if (ImportDefaultValue&& isImportRows && string.IsNullOrEmpty(dataRow[col.FieldName] + "") && !string.IsNullOrEmpty(model.DefaultValue)) //{ // dataRow[col.FieldName] = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(dataRow, model.DefaultValue)); // if (!string.IsNullOrEmpty(model.UnionFields)) // { // SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); // } //} } table.Rows.Add(dataRow); } ToAssignment = false; } catch (InvalidOperationException ex) { if (ToAssignment && (CurrentRow != 0 || CurrentColumn != 0)) { string value = string.Format("第{0}行,第{1}列 {2},值出现异常", CurrentRow, CurrentColumn + 1, columnName); MessageUtil.Show(value); } else { MessageUtil.Show(ResourceKeys.DeleteLastTotalRow); } } catch (IOException exe) { //string Message = ErrorMessage.PromptErrorMessage(exe); //MessageUtil.Show(Message, exe.Message); MessageUtil.Show(string.Format(ResourceKeys.UseingFile, Path.GetFileName(fileName))); } catch (Exception ex) { //MessageUtil.Show(ResourceKeys.ImportFault + ex.Message); LogUtil.WriteError("读取excel出错!", ex); string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } return table.TrimEmptyRows(); } public static bool QuickImport(this GridView gridView, ModuleModel SysModel, string parmaryKey, string leftField, string leftValue,List ImportReturnName, List ImportReturnValue, GridControlEx ParentGridEx=null ) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = "选择导入文件"; // dialog.Filter = "Excel|*.xls|Excel|*.xlsx"; dialog.Filter = SystemInfo.Instance.IsXlsxFirst ? "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls" : "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx"; DialogResult ImportResult = dialog.ShowDialog(); DataTable ImportTable = new DataTable(); if (ImportResult == DialogResult.OK) { string _importFlag = "lskjimport_errorFlag"; DataTable tableColumns = BaseModuleImpl.GetBaseGridColumns(SysModel.ModeCode); GridControlEx gridControlEx = new GridControlEx(); if (gridView is BandedGridView && tableColumns != null && tableColumns.Rows.Count > 0) { gridControlEx = new BandedGridControlEx(); (gridControlEx as BandedGridControlEx).moduleModel = SysModel; gridControlEx.SetReadOnlyColumns(tableColumns, GridCustomColumnStruct.BaseMainGridView + SysModel.FormKey); GridBand gridBand = new GridBand(); gridBand.Caption = "导入消息"; gridBand.AppearanceHeader.Options.UseFont = true; gridBand.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; (gridControlEx.GridView as BandedGridView).Bands.AddRange(new GridBand[] { gridBand }); //BandedGridColumn BandedGridColumn colMsg = new BandedGridColumn(); colMsg.Tag = null; colMsg.FieldName = "import_errormsg"; colMsg.Width = 200; colMsg.Caption = "导入错误信息"; colMsg.Visible = true; colMsg.OwnerBand = gridBand; gridControlEx.GridView.Columns.Add(colMsg); BandedGridColumn RegressionMsg = new BandedGridColumn(); RegressionMsg.Tag = null; RegressionMsg.FieldName = _importFlag; RegressionMsg.Width = 200; RegressionMsg.Caption = "是否导入成功"; RegressionMsg.Visible = true; RegressionMsg.OwnerBand = gridBand; gridControlEx.GridView.Columns.Add(RegressionMsg); } else { gridControlEx.SetEditColumns(tableColumns, GridCustomColumnStruct.BaseMainGridView + SysModel.FormKey); gridControlEx.GridView.OptionsBehavior.Editable = false;//禁止编辑 GridColumn colMsg = new GridColumn(); colMsg.Tag = null; colMsg.FieldName = "import_errormsg"; colMsg.Width = 200; colMsg.Caption = "导入错误信息"; colMsg.Visible = true; gridControlEx.GridView.Columns.Add(colMsg); GridColumn RegressionMsg = new GridColumn(); RegressionMsg.Tag = null; RegressionMsg.FieldName = _importFlag; RegressionMsg.Width = 200; RegressionMsg.Caption = "是否导入成功"; RegressionMsg.Visible = true; gridControlEx.GridView.Columns.Add(RegressionMsg); } if (!BaseImpl.HasExistsColumn(SysModel.MenuTable,_importFlag)) { BaseImpl.ExecSqlValue(string.Format("alter table {0} add {1} varchar(20) default('0')", SysModel.MenuTable, _importFlag)); } string fileName = dialog.FileName; string colFields = gridControlEx.GridView.Columns.ToString(','); ImportTable = gridControlEx.GridView.ToExcelDataTable(fileName, colFields, true); if (ImportTable==null&&ImportTable.Rows.Count < 1) { MessageBox.Show("没有任何数据可以进行导入", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } //if (MessageUtil.Show("如果导入数据量太多将花费较长时间,是否确认导入", MessageBoxButtons.YesNo) != DialogResult.Yes) // return false; //设置默认值 if (SystemInfo.Instance.ImportDefaultValue) { foreach (GridColumn col in gridControlEx.GridView.Columns) { if (!ImportTable.Columns.Contains(col.FieldName)) ImportTable.Columns.Add(col.FieldName); } foreach (DataRow rowItem in ImportTable.Rows) { foreach (GridColumn col in gridControlEx.GridView.Columns) { // 未包含字段,则使用控件默认值. GridColumnModel model = col.Tag as GridColumnModel; if (model != null && !string.IsNullOrEmpty(model.DefaultValue)) { if (!string.IsNullOrEmpty(rowItem[col.FieldName] + "")) continue; string fieldValue = ReplaceHelper.ReplaceRowParam(rowItem, model.DefaultValue); if (ParentGridEx != null) { DataRow SelectTheLine = ParentGridEx.GetViewFocusedDataRow(); fieldValue = ReplaceHelper.ReplaceRowParam(SelectTheLine, fieldValue); } fieldValue = BaseImpl.GetDefaultValue(fieldValue); if (!string.IsNullOrEmpty(fieldValue)) { rowItem[col.FieldName] = fieldValue; if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, rowItem[col.FieldName] + "", rowItem); } } } } } } //判断导入条件 if (!string.IsNullOrEmpty(SysModel.ImportConditions)) { List ErrorLine = new List(); int currRow = 0; foreach (DataRow dr in ImportTable.Rows) { currRow++; string cond = ReplaceHelper.ReplaceRowParam(dr, SysModel.ImportConditions); if (ParentGridEx != null) { DataRow SelectTheLine = ParentGridEx.GetViewFocusedDataRow(); cond = ReplaceHelper.ReplaceRowParam(SelectTheLine, cond); } bool result = false; if (cond.StartsWith("@") || cond.StartsWith("!")) { result = "1".Equals(BaseImpl.GetDefaultValue(cond)); } else { result = ReplaceHelper.ReplaceRowParamCond(dr, cond); } if (!result) { ErrorLine.Add(currRow); } } if (ErrorLine.Count > 0) { XtraMessageBox.Show("导入失败,第" + String.Join(", ", ErrorLine) + "条不满足条件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } } //开始导入 //提交到数据库 string rowNum = "0"; string colNum = "0"; string colName = ""; int success = 0; int failed = 0; List _calcFields = new List(); DataTable dtCalcFields = BaseImpl.GetDataTableResult(string.Format("select name from sys.columns where object_id=object_id('{0}') and is_computed=1", SysModel.MenuTable)); if ((dtCalcFields != null) && (dtCalcFields.Rows.Count > 0)) { foreach (DataRow dr in dtCalcFields.Rows) { _calcFields.Add(dr[0] + ""); } } try { string sql = "select * from " + SysModel.MenuTable + " where 1<>1"; SqlDataAdapter dat = BaseImpl.GetAdapterResult(sql); SqlCommandBuilder scb = new SqlCommandBuilder(dat); DataTable datatb = new DataTable(); DataTable failedData = new DataTable(); dat.Fill(datatb); if (ImportReturnName.Count > 0) { foreach (string item in ImportReturnName) { if (!ImportTable.Columns.Contains(item)) ImportTable.Columns.Add(item); } } failedData = ImportTable.Clone(); if (!failedData.Columns.Contains("import_errormsg")) failedData.Columns.Add("import_errormsg"); if (!failedData.Columns.Contains(_importFlag)) failedData.Columns.Add(_importFlag); for (int i = 0; i < ImportTable.Rows.Count; i++) { ImportTable.Rows[i][_importFlag] = "1"; if (ImportReturnName.Count > 0) { for (int j = 0; j < ImportReturnName.Count; j++) { string name = ImportReturnName[j]; string Value = ImportReturnValue[j]; ImportTable.Rows[i][name] = Value; } } } //所有导入的主键集合 List parmaryKeys = new List(); //根据全表字段类型进行默认填充 int currRow = 0; foreach (DataRow dr in ImportTable.Rows) { if (SysModel.ImportPrimarykeyVerify && !string.IsNullOrWhiteSpace(parmaryKey)) { if (parmaryKeys.Contains(dr[parmaryKey])) { continue; } else { parmaryKeys.Add(dr[parmaryKey] + ""); } } rowNum = (currRow + 1) + ""; DataRow tmpRow = datatb.NewRow(); foreach (DataColumn dc in datatb.Columns) { if (dc.DataType.Name.ToLower() == "string") tmpRow[dc] = ""; if (dc.DataType.Name.ToLower().IndexOf("char") >= 0) tmpRow[dc] = ""; if (dc.DataType.Name.ToLower().IndexOf("int") >= 0) tmpRow[dc] = 0; if (dc.DataType.Name.ToLower() == "decimal") tmpRow[dc] = 0; } foreach (GridColumn gc in gridControlEx.GridView.Columns) { if (_calcFields.IndexOf(gc.FieldName) != -1) continue; if (datatb.Columns.Contains(gc.FieldName) && ImportTable.Columns.Contains(gc.FieldName)) { colName = gc.Caption; colNum = (gc.VisibleIndex + 1) + ""; GridColumnModel model = gc.Tag as GridColumnModel; bool isEmpty = false; if (model != null) { isEmpty = model.CanNull; } if (model != null && (model.FieldType == ControlType.LabTreeType || model.FieldType == ControlType.LabComboxValue || model.FieldType == ControlType.LabComboxValueParam || model.FieldType == ControlType.LabAutoCompleteValue || model.FieldType == ControlType.LabAutoCompleteValueParam || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabAutoGridValue || model.FieldType == ControlType.LabSelectReturnId )) { string fieldValue = GetValueByImportText(dr, gc.FieldName, dr[gc.FieldName] + ""); if (!string.IsNullOrEmpty(fieldValue)) { tmpRow[gc.FieldName] = fieldValue; } } else if (model != null && (model.FieldType == ControlType.LabDate || model.FieldType == ControlType.LabDateTime || model.FieldType == ControlType.LabDateTimeShort || model.FieldType == ControlType.LabTime || model.FieldType == ControlType.LabShortTime)) { string fieldValue = ToDateTimeValue(dr[gc.FieldName].ToString().Trim()); if (!string.IsNullOrEmpty(fieldValue)) { tmpRow[gc.FieldName] = fieldValue; } } else if (model != null && (model.FieldType == ControlType.LabRemark) && !dr[gc.FieldName].ToString().Contains("\r\n")) { string fieldValue = dr[gc.FieldName].ToString().Replace("\n", "\r\n"); if (!string.IsNullOrEmpty(fieldValue)) { tmpRow[gc.FieldName] = fieldValue; } } //排除数值型导入空值的可能 else if (dr[gc.FieldName].ToString().Trim() != "") { GridColumn column = gridControlEx.GridView.Columns[gc.FieldName]; if (dr[gc.FieldName].ToString().Trim() == "校验") tmpRow[gc.FieldName] = "1"; else if (dr[gc.FieldName].ToString().Trim() == "非校验") tmpRow[gc.FieldName] = "0"; string fieldValue = SystemInfo.Instance.ImportReservedSpaces ? dr[gc.FieldName].ToString() : dr[gc.FieldName].ToString().Trim(); if (fieldValue == "是" || fieldValue == "否") { if (column.ColumnEdit != null && column.ColumnEdit.GetType() == typeof(RepositoryItemCheckEdit)) { tmpRow[gc.FieldName] = "1"; } else if (column.ColumnType != null && column.ColumnType.Name.ToLower() == "boolean") { tmpRow[gc.FieldName] = true; } else { tmpRow[gc.FieldName] = fieldValue; } } else { tmpRow[gc.FieldName] = fieldValue; } } } } setDefaultValue(datatb, tmpRow, SysModel.PrefixKey); //if (mainKeyField != "") // tmpRow[mainKeyField] = mainKeyValue; if (SysModel.ConcatenatedPrefix) { if (datatb.Columns.Contains(SysModel.PrefixKey + leftField) && !string.IsNullOrWhiteSpace(leftValue) && SysModel.AssociationLeft) { if (string.IsNullOrEmpty(tmpRow[SysModel.PrefixKey + leftField] + "") || (tmpRow[SysModel.PrefixKey + leftField] + "").Equals("0")) { tmpRow[SysModel.PrefixKey + leftField] = leftValue; } } } else { if (datatb.Columns.Contains(leftField) && !string.IsNullOrWhiteSpace(leftValue) && SysModel.AssociationLeft) { if (string.IsNullOrEmpty(tmpRow[SysModel.PrefixKey + leftField] + "") || (tmpRow[SysModel.PrefixKey + leftField] + "").Equals("0")) { tmpRow[SysModel.PrefixKey + leftField] = leftValue; } } } foreach (GridColumn gc in gridControlEx.GridView.Columns) { if (tmpRow.Table.Columns.Contains(gc.FieldName)) { string fieldValue = tmpRow[gc.FieldName] + ""; GridColumnModel model = gc.Tag as GridColumnModel; if (model != null) { if (model.CanNull && string.IsNullOrEmpty(fieldValue))//必填 { XtraMessageBox.Show("数据导入错误,数据不能为空,请检查!\r\n第" + (currRow + 1).ToString() + "行,第" + (gc.VisibleIndex + 1).ToString() + "列-" + gc.Caption, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } } } } datatb.Rows.Add(tmpRow); try { dat.Update(datatb); datatb.AcceptChanges(); success++; } catch (Exception ex) { dr.RowError = ex.Message; dr["import_errormsg"] = ex.Message; failedData.ImportRow(dr); datatb.Rows.Remove(tmpRow); failed++; //string Message = ErrorMessage.PromptErrorMessage(ex); //MessageUtil.Show(Message, ex.Message); break; } currRow++; } ImportTable.AcceptChanges(); XtraMessageBox.Show("数据导入完成,成功" + success.ToString() + "条,失败" + failed.ToString() + "条", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (failedData.Rows.Count > 0) { MessageUtil.Show(failedData.Rows[0]["import_errormsg"].ToString()); string sqlValue2 = string.Format("delete from {0} where {1}='1'", SysModel.MenuTable, _importFlag); SqlHelper.ExecuteNonQuery(sqlValue2); } string sqlValue = string.Format("update {0} set {1}='0' ", SysModel.MenuTable, _importFlag); sqlValue = string.Format("update {0} set {1}='0' where {1}!='0' ", SysModel.MenuTable, _importFlag); SqlHelper.ExecuteNonQuery(sqlValue); DataRow dataRow = datatb.Rows[0]; if (!string.IsNullOrWhiteSpace(SysModel.afterimportSql2) && failed == 0) { SqlHelper.ExecuteNonQuery(ReplaceHelper.ReplaceRowParam(dataRow, ReplaceHelper.ReplaceUserInfo(SysModel.afterimportSql2))); } datatb.Clear(); LogUtil.WriteDebug(SysModel.ModeCode, "导入数据", SysModel.MenuText, "数据导入,成功" + success.ToString() + "条,失败" + failed.ToString() + "条"); } catch (Exception ex) { string mesage = ex.Message; string sqlValue = string.Format("delete from {0} where {1}='1'", SysModel.MenuTable, _importFlag); SqlHelper.ExecuteNonQuery(sqlValue); foreach (GridColumn gc in gridControlEx.GridView.Columns) { if (ex.Message.Contains(gc.FieldName)) { mesage = gc.Caption + " 格式不正确,请检查!"; break; } } string errorMsg = string.Format("{0}\r\n第{1}行,第{2}列\r\n列名:{3}", mesage, rowNum, colNum, colName); XtraMessageBox.Show("数据提交错误:\n" + errorMsg + "\r\n", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } return true; } return false; } /// /// 查找当前是否存在指定值 /// /// /// /// private static void setDefaultValue(DataTable dtTable, DataRow currentRow,string _qzKey) { if ((dtTable.Columns.Contains(_qzKey + "operatorid")) && ((string.IsNullOrEmpty(currentRow[_qzKey + "operatorid"] + "") || currentRow[_qzKey + "operatorid"] + "" == "0"))) currentRow[_qzKey + "operatorid"] = ERPInfo.Instance.UserId; if ((dtTable.Columns.Contains(_qzKey + "operatorname")) && ((string.IsNullOrEmpty(currentRow[_qzKey + "operatorname"] + "") || currentRow[_qzKey + "operatorname"] + "" == "0"))) currentRow[_qzKey + "operatorname"] = ERPInfo.Instance.UserName; if ((dtTable.Columns.Contains(_qzKey + "operatedate")) && ((string.IsNullOrEmpty(currentRow[_qzKey + "operatedate"] + "") || currentRow[_qzKey + "operatedate"] + "" == "0"))) currentRow[_qzKey + "operatedate"] = DateTime.Now; } /// /// 说明:计算列关联字段 /// 创建人:龚宇超 /// 创建日期:2017-12-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// The field value. private static void SetUnionValue(GridColumnModel model, string fieldValue, DataRow rowItem) { //DataTable table = gcMain.gridControl.DataSourceTable(); //DataRow rowItem = this.gridView.GetFocusedDataRow(); string unionValues = model.UnionValues; if (rowItem != null && model != null) { // if (this.ControlObj != null) // unionValues = this.ControlObj.ReplaceParentControlValue(unionValues); unionValues = ReplaceHelper.ReplaceRowParam(rowItem, unionValues.Replace("{" + model.FieldName + "}", fieldValue)); try { string[] fields = model.UnionFields.Trim(',').Split(','); DataRow rowResult = BaseImpl.GetDataRowResult(unionValues); if (rowResult != null) { for (int i = 0; i < fields.Length; i++) { string field = fields[i]; string value = rowResult.Table.Columns.Contains(field) ? rowResult[field] + "" : null; rowItem[field] = value; } } else { // 设置为空 for (int i = 0; i < fields.Length; i++) { string field = fields[i]; rowItem[field] = DBNull.Value; } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("计算列关联字段--错误-->" + unionValues, ex); } } } /// /// 说明:计算列计算公式 /// 创建人:龚宇超 /// 创建日期:2017-12-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// The field value. private static void SetCalcValue(GridColumnModel model, string fieldValue, DataRow rowItem) { try { if (rowItem != null && model != null) { List calcModels = ColumnList.FindAll(x => !string.IsNullOrEmpty(x.CalcExpr)).OrderBy(y => y.CalcOrder).ToList(); foreach (GridColumnModel gridModel in calcModels) { // 计算顺序小于当前控件则不计算 if (gridModel.CalcOrder < model.CalcOrder) continue; if (!gridModel.FieldName.Equals(model.FieldName, StringComparison.OrdinalIgnoreCase)) { bool isTruncate = false; string calcExpr = gridModel.CalcExpr; if (calcExpr.StartsWith("@truncate:")) { calcExpr = calcExpr.Substring(10); isTruncate = true; } try { //if (this.ParentControl != null) // calcExpr = ParentControl.ReplaceParentControlValue(calcExpr); string result = string.Empty; if (calcExpr.StartsWith("@")) { result = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, calcExpr)); } else { calcExpr = ReplaceHelper.ReplaceRowParam(rowItem, calcExpr); //EvalHelper.Eval2(ReplaceHelper.ReplaceEvalCond(calcExpr)) + "" result = EvalHelper.Eval2(ReplaceHelper.ReplaceEvalCond(calcExpr)) + ""; } if (isTruncate) { result += result.Contains(".") ? "0000000000" : ".0000000000"; rowItem[gridModel.FieldName] = result.Substring(0, result.IndexOf(".")) + result.Substring(result.IndexOf("."), model.Decimals + 1); //this.gridView.SetRowCellValue(this.gridView.FocusedRowHandle, this.gridView.Columns[gridModel.FieldName], result.Substring(0, result.IndexOf(".")) + result.Substring(result.IndexOf("."), model.Decimals + 1)); } else { try { double d = 0; if (!string.IsNullOrEmpty(result) && !"NaN".Equals(result, StringComparison.OrdinalIgnoreCase) && !"非数字".Equals(result, StringComparison.OrdinalIgnoreCase) && !"undefined".Equals(result, StringComparison.OrdinalIgnoreCase) && result != "∞" && result != "-∞" && !"正无穷大".Equals(result, StringComparison.OrdinalIgnoreCase) && !"负无穷大".Equals(result, StringComparison.OrdinalIgnoreCase) && double.TryParse(result, out d)) { if (string.IsNullOrEmpty(gridModel.DataFormat)) { result = Math.Round(Convert.ToDouble(d), model.Decimals, MidpointRounding.AwayFromZero) + ""; } else { //计算后先执行保存小数位数 result = string.Format("{0:" + gridModel.DataFormat + "}", Convert.ToDecimal(result)); } if (model.FieldType == 7 && result.Contains('%')) { result = (double.Parse(result.Replace("%", "")) * 0.01).ToString(); } rowItem[gridModel.FieldName] = result; // 判断计算列有无关联值 GridColumnModel UnionModel = calcModels.FirstOrDefault(x => x.FieldName == gridModel.FieldName); if (!string.IsNullOrEmpty(UnionModel.UnionFields)) { SetUnionValue(UnionModel, rowItem[gridModel.FieldName] + "", rowItem); } //this.gridView.SetRowCellValue(this.gridView.FocusedRowHandle, this.gridView.Columns[gridModel.FieldName], result); } } catch (Exception) { } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("计算列计算公式--错误-->" + rowItem[gridModel.FieldName], ex); } } } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); string Message = ErrorMessage.PromptErrorMessage(ex); // MessageUtil.Show(Message,ex.Message); } finally { // this.GridSumming = false; } } /// /// 说明:导入表的时候将下拉框的值存储 /// 创建人:王一帆 /// 创建日期:2020-04-21 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0.0.3 /// /// The col fields. private static void InitializeValueGrid(this GridView gridView) { ValueGridColumnTable = new Dictionary(); _checkColumns = new List(); LookupParentKey = new Dictionary(); foreach (GridColumn col in gridView.Columns) { if (col.Tag is GridColumnModel) { GridColumnModel model = col.Tag as GridColumnModel; if (model != null && !ValueGridColumnTable.ContainsKey(model)) { if (model.FieldType == ControlType.LabTreeType || model.FieldType == ControlType.LabComboxValue || model.FieldType == ControlType.LabComboxValueParam || model.FieldType == ControlType.LabAutoCompleteValue || model.FieldType == ControlType.LabAutoCompleteValueParam || model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabTreeLookValue || model.FieldType == ControlType.LabCheckBox || model.FieldType == ControlType.LabAutoGridValue || model.FieldType == ControlType.LabAutoGridValueParam || model.FieldType == ControlType.LabSelectReturnId ) { string sqlValue = model.SqlSource; if (model.FieldType == ControlType.LabSelectReturnId) { if (model.IsRadio && !string.IsNullOrWhiteSpace(model.addModuleld)) { //单选模式数据源为模块sql DataRow modelRow = Business.Impl.MainImpl.GetSystemdllTab(model.addModuleld); sqlValue = modelRow["SQL"] + ""; } } if (sqlValue.Contains(" #")) { //sqlValue = sqlValue.Replace("#", ""); Match m = Regex.Match(sqlValue, @"#([\s\S]*?)#"); //处理带参数上一级编码过滤问题,需在带参数sql中增加名称的父级字段 if (m.Success) { sqlValue = ReplaceHelper.ReplaceParam(sqlValue); LookupParentKey.Add(model.FieldName, m.Value.Replace("#", "")); } } ValueGridColumnTable.Add(model, BaseImpl.GetDataTableResult(sqlValue)); if (model.FieldType == ControlType.LabTreeType) { _treeColumnName = model.FieldName; } } if (model.FieldType == ControlType.LabCheckBox) { _checkColumns.Add(col.FieldName.ToLower()); } } } } } /// /// 说明:导入表的时候将下拉框的值存储 /// 创建人:王一帆 /// 创建日期:2020-04-21 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0.0.3 /// /// The col fields. private static void InitializeValueGrid(TreeList treeList) { ValueGridColumnTable = new Dictionary(); _checkColumns = new List(); LookupParentKey = new Dictionary(); foreach (TreeListColumn col in treeList.Columns) { if (col.Tag is GridColumnModel) { GridColumnModel model = col.Tag as GridColumnModel; if (model != null && !ValueGridColumnTable.ContainsKey(model)) { if (model.FieldType == ControlType.LabTreeType || model.FieldType == ControlType.LabComboxValue || model.FieldType == ControlType.LabComboxValueParam || model.FieldType == ControlType.LabAutoCompleteValue || model.FieldType == ControlType.LabAutoCompleteValueParam || model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabTreeLookValue || model.FieldType == ControlType.LabCheckBox || model.FieldType == ControlType.LabAutoGridValue || model.FieldType == ControlType.LabAutoGridValueParam || model.FieldType == ControlType.LabSelectReturnId ) { string sqlValue = model.SqlSource; if (sqlValue.Contains(" #")) { //sqlValue = sqlValue.Replace("#", ""); Match m = Regex.Match(sqlValue, @"#([\s\S]*?)#"); //处理带参数上一级编码过滤问题,需在带参数sql中增加名称的父级字段 if (m.Success) { sqlValue = ReplaceHelper.ReplaceParam(sqlValue); LookupParentKey.Add(model.FieldName, m.Value.Replace("#", "")); } } ValueGridColumnTable.Add(model, BaseImpl.GetDataTableResult(sqlValue)); if (model.FieldType == ControlType.LabTreeType) { _treeColumnName = model.FieldName; } } if (model.FieldType == ControlType.LabCheckBox) { _checkColumns.Add(col.FieldName.ToLower()); } } } } } /// /// 数字转换时间格式 /// /// 数字,如:42095.7069444444/0.650694444444444 /// 日期/时间格式 private static string ToDateTimeValue(string strNumber) { if (!string.IsNullOrWhiteSpace(strNumber)) { Decimal tempValue; //先检查 是不是数字; if (Decimal.TryParse(strNumber, out tempValue)) { //天数,取整 int day = Convert.ToInt32(Math.Truncate(tempValue)); //这里也不知道为什么. 如果是小于32,则减1,否则减2 //日期从1900-01-01开始累加 // day = day < 32 ? day - 1 : day - 2; DateTime dt = new DateTime(1900, 1, 1).AddDays(day < 32 ? (day - 1) : (day - 2)); //小时:减掉天数,这个数字转换小时:(* 24) Decimal hourTemp = (tempValue - day) * 24;//获取小时数 //取整.小时数 int hour = Convert.ToInt32(Math.Truncate(hourTemp)); //分钟:减掉小时,( * 60) //这里舍入,否则取值会有1分钟误差. Decimal minuteTemp = Math.Round((hourTemp - hour) * 60, 2);//获取分钟数 int minute = Convert.ToInt32(Math.Truncate(minuteTemp)); //秒:减掉分钟,( * 60) //这里舍入,否则取值会有1秒误差. Decimal secondTemp = Math.Round((minuteTemp - minute) * 60, 2);//获取秒数 int second = Convert.ToInt32(Math.Truncate(secondTemp)); //时间格式:00:00:00 string resultTimes = string.Format("{0}:{1}:{2}", (hour < 10 ? ("0" + hour) : hour.ToString()), (minute < 10 ? ("0" + minute) : minute.ToString()), (second < 10 ? ("0" + second) : second.ToString())); if (day > 0) return string.Format("{0} {1}", dt.ToString("yyyy-MM-dd"), resultTimes); else return resultTimes; } else { return strNumber; } } return string.Empty; } /// /// 说明:获取Grid列,按xxx字符分割 /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The columns. public static string ToString(this GridColumnCollection columns, char spiltChar) { string fields = string.Empty; foreach (GridColumn col in columns) { fields += col.FieldName + spiltChar; } return fields.TrimEnd(spiltChar); } /// /// 说明:获取Grid列,判断是否是必填列 /// 创建人:王一帆 /// 创建日期:2020-12-17 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The columns. public static bool isRequiredFields(this GridControl control, string requiredFields, GridView gridView) { if (!string.IsNullOrEmpty(requiredFields)) { string[] Fields = requiredFields.TrimEnd(',').Split(','); foreach (string requiredField in Fields) { DataTable dt = control.DataSourceTable(); //if (dt.Rows.Cast().FirstOrDefault(x => x[requiredField] + "" == string.Empty) != null) //{ // MessageUtil.Show(string.Format("明细列:{0}不能为空!", gridView.Columns[requiredField].Caption)); // return false; //} for (int i = 0; i < dt.Rows.Count; i++) { if (string.IsNullOrWhiteSpace(gridView.GetRowCellDisplayText(i, requiredField))) { MessageUtil.Show(string.Format("明细列:{0}不能为空!", gridView.Columns[requiredField].Caption)); return false; } } } } return true; } /// /// 说明:单元格合并 /// 创建人:王一帆 /// 创建日期: /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. private static void OnGridViewCellMerge(object sender, CellMergeEventArgs e) { try { GridView gridView = sender as GridView; GridColumn column = e.Column; GridColumnModel model = column.Tag as GridColumnModel; if (model == null || string.IsNullOrEmpty(model.MergeGroup)) return; string[] fields = model.MergeGroup.Trim(',').Split(','); for (int i = 0; i < fields.Length; i++) { int row1 = e.RowHandle1; int row2 = e.RowHandle2; string McColumn = fields[i] + "";//关联条件列 string value1 = gridView.GetDataRow(row1)[McColumn].ToString(); string value2 = gridView.GetDataRow(row2)[McColumn].ToString(); if (value1 != value2) { e.Handled = true; } else { e.Handled = false; } } } catch (Exception ex) { //string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); //MessageUtil.Show(Message, ex.Message); //LogHelper.Instance.WriteError(ex); } } /// /// 导出数据的第一行添加模块名称 /// /// private static void SetModuleName(string excelFilePath, string fileExt, int NumberOfColumns, bool isBanded = false, PanelControl panel = null) { try { //条件信息 string condition = string.Empty; if (panel != null && panel.Visible) { foreach (System.Windows.Forms.Control item in panel.Controls) { if (item is BaseUserControl) { BaseUserControl baseUser = item as BaseUserControl; condition += string.Format("{0}={1} ", baseUser.LabelText, baseUser.EditText); } } } //插入行数 int InsertRows = 1; if (!string.IsNullOrWhiteSpace(condition)) { InsertRows = 2; condition = "条件: " + condition; } IWorkbook workbook; if (fileExt.Equals(".xls")) { using (FileStream file = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read)) { workbook = new HSSFWorkbook(file); // 适用于.xlsx格式 } } else if (fileExt.Equals(".xlsx")) { using (FileStream file = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read)) { workbook = new XSSFWorkbook(file); // 适用于.xlsx格式 } } else { return; } ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表 // 第一行的索引 int newRowNum = sheet.FirstRowNum; // 向下移动所有行(包括第一行),为新行腾出空间 sheet.ShiftRows(newRowNum, sheet.LastRowNum, InsertRows); // 设置筛选器位置(多表头不用设置) if (!isBanded) { int lastRowNum = sheet.LastRowNum; var range = new CellRangeAddress(InsertRows, lastRowNum, 0, sheet.GetRow(1).LastCellNum - 1);//设置到第二行 sheet.SetAutoFilter(range); // 设置新的筛选器范围 } for (int i = 0; i < InsertRows; i++) { //添加行 IRow newRow = sheet.CreateRow(newRowNum + i); // 合并新插入的行的全部列 CellRangeAddress cellRangeAddress = new CellRangeAddress( newRowNum + i, // 开始行 newRowNum + i, // 结束行 0, // 开始列 NumberOfColumns - 1 // 结束列 ); sheet.AddMergedRegion(cellRangeAddress); // 合并单元格 // 在合并后的单元格中添加内容(通常只需在合并区域的起始位置设置) ICell cell = newRow.CreateCell(0); // 添加内容 if (i == 0) { string guid = ERPInfo.Instance.PageControl.SelectedTabPage.Tag + ""; DllModule model = ERPInfo.Instance.ModuleForms[guid]; cell.SetCellValue(model.Name); } else if (i == 1) { cell.SetCellValue(condition); } // 设置单元格样式为居中 ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; // 水平居中 cellStyle.VerticalAlignment = VerticalAlignment.Center; // 垂直居中 // 设置字体加粗和大小 IFont font = workbook.CreateFont(); font.Boldweight = (short)FontBoldWeight.Bold; // 设置字体为加粗 font.FontHeightInPoints = 14; cellStyle.SetFont(font); //多表格设置背景颜色(和原第一行,现在第二行的背景颜色相同) if (isBanded) { cellStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index; // 设置填充模式为实心填充 cellStyle.FillPattern = FillPattern.SolidForeground; }