/****************************** * 说明:导入Excel * 创建人:龚宇超 * 创建日期:2017-11-15 * 修改人: * 修改日期: * 修改备注: * 版本:1.0.0.0 ******************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Lskj.Control.Model; using DevExpress.XtraGrid.Columns; using Lskj.Util; using Lskj.Data; using System.IO; //using NPOI.SS.UserModel; using System.Collections; using Lskj.Model; using Lskj.Business.Impl; using System.Text.RegularExpressions; using Lskj.Business; using DevExpress.XtraEditors; using System.Data.SqlClient; using DevExpress.XtraEditors.Repository; using Lskj.Core; //using NPOI.SS.Util; //using NPOI; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI; using System.Diagnostics; using DevExpress.XtraGrid.Views.BandedGrid; using DevExpress.Utils; using Lskj.Control; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using DevExpress.XtraGrid.Views.Grid; using Newtonsoft.Json.Linq; using System.Web; using Lskj.Control.BrowserSetting; using System.Net; using Newtonsoft.Json; namespace Lskj.PubBomImportNew { /// /// 导入Excel /// public partial class FrmMain2 : BaseForm { public FrmMain2() { InitializeComponent(); } public DynamicBomImportNew Model; /// /// 判断是否是导入后的数据 /// private string _importFlag = "lskjimport_errorFlag"; /// /// 是否导入过记录 /// private bool _isImported; /// /// 表名 /// private string _tableName; /// /// 模块编号 /// private string _menuCode; /// /// 模块名称 /// private string _fromText; /// /// 主键字段 /// private string _parmaryKey; private string _qzKey; private string _primkey, _keyvalue; private string _treeColumnName; private int success = 0, failed = 0; private ModuleModel SysModel; private List _checkColumns; private DataTable _tableColumns; /// /// 拼接前缀 /// private bool concatenatedPrefix; /// /// Occurs when [on import click]. /// public event EventHandler OnImportClick; public DataColumnCollection SourceColumns = null; public Dictionary ValueGridColumnTable; public Dictionary LookupParentKey; public List _calcFields; /// /// 父容器表格 /// public GridControlEx ParentGridEx; /// /// 缓存列对象 /// private static List ColumnList = new List(); /// /// 源表格 /// private GridControlEx _gridEx; /// /// 导入返回控件名 /// public List ImportReturnName = new List(); /// /// 导入返回控件值 /// public List ImportReturnValue = new List(); public int FirstRowIndex = 0; /// /// 选择的文件 /// public string FilePath; protected override void OnLoad(EventArgs e) { this.Opacity = 1; int.TryParse(Model.stratRowHand + "", out FirstRowIndex); DataRow modelRow = MainImpl.GetSystemdllTab(Model.UnionModelCode);//获取模块信息 if (modelRow != null) { this.SysModel = new ModuleModel(modelRow); InitializeControl(this.SysModel.MenuTable, this.Model.UnionModelCode, _parmaryKey, this.gcMain, this.SysModel.PrefixKey, this.Model.primkey, this.Model.keyvalue, this.Model.FormText, this.SysModel.ConcatenatedPrefix); } else { MessageUtil.Show("请检查模板是否配置正确!"); } } public void InitializeControl(string tableName, string menuCode, string parmaryKey, GridControlEx gridEx, string qzKey, string primkey, string keyvalue, string Fromtext, bool ConcatenatedPrefix = true) { try { this._tableColumns = BaseModuleImpl.GetBaseGridColumns(menuCode); this._tableName = tableName; this._menuCode = menuCode; this._parmaryKey = parmaryKey; this._gridEx = gridEx; this._qzKey = qzKey; this._primkey = primkey; this._keyvalue = keyvalue; this._calcFields = new List(); this._fromText = Fromtext; this.concatenatedPrefix = ConcatenatedPrefix; DataRow modelRow = MainImpl.GetSystemdllTab(_menuCode);//获取单个模块信息 if (modelRow != null) { SysModel = new ModuleModel(modelRow);// 系统模块实体对象 } bool isAdmin = ERPInfo.Instance.UserName.Equals("管理员"); this.btnCover.Visible = SysModel == null ? isAdmin : isAdmin ? true : SysModel.OperPermissionsUser.Contains(ERPInfo.Instance.UserName); this.SourceColumns = BaseImpl.GetDataTableResult(string.Format("select * from {0} where 1<>1", _tableName)).Columns; DataTable dtCalcFields = BaseImpl.GetDataTableResult(string.Format("select name from sys.columns where object_id=object_id('{0}') and is_computed=1", _tableName)); if ((dtCalcFields != null) && (dtCalcFields.Rows.Count > 0)) { foreach (DataRow dr in dtCalcFields.Rows) { _calcFields.Add(dr[0] + ""); } } this.InitializeGrid(); this.InitializeValueGrid(); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:初始化GridControl /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void InitializeGrid() { if (this._gridEx != null) { this.gcMain.GridView.Columns.Clear(); if (this._gridEx is BandedGridControlEx && this._tableColumns != null && this._tableColumns.Rows.Count > 0) { this.pl_main.Controls.Clear(); this.gcMain = new BandedGridControlEx(); (this.gcMain as BandedGridControlEx).moduleModel = this.SysModel; this.gcMain.Dock = DockStyle.Fill; this.pl_main.Controls.Add(this.gcMain); this.gcMain.SetReadOnlyColumns(_tableColumns, GridCustomColumnStruct.BaseMainGridView + this.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; (this.gcMain.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; this.gcMain.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; this.gcMain.GridView.Columns.Add(RegressionMsg); } else { this.gcMain.SetEditColumns(_tableColumns, GridCustomColumnStruct.BaseMainGridView + this.SysModel.FormKey); this.gcMain.GridView.OptionsBehavior.Editable = false;//禁止编辑 GridColumn colMsg = new GridColumn(); colMsg.Tag = null; colMsg.FieldName = "import_errormsg"; colMsg.Width = 200; colMsg.Caption = "导入错误信息"; colMsg.Visible = true; this.gcMain.GridView.Columns.Add(colMsg); GridColumn RegressionMsg = new GridColumn(); RegressionMsg.Tag = null; RegressionMsg.FieldName = _importFlag; RegressionMsg.Width = 200; RegressionMsg.Caption = "是否导入成功"; RegressionMsg.Visible = true; this.gcMain.GridView.Columns.Add(RegressionMsg); } if (!BaseImpl.HasExistsColumn(this._tableName, this._importFlag)) { BaseImpl.ExecSqlValue(string.Format("alter table {0} add {1} varchar(20) default('0')", _tableName, _importFlag)); } } } private void InitializeValueGrid() { this.ValueGridColumnTable = new Dictionary(); this._checkColumns = new List(); this.LookupParentKey = new Dictionary(); foreach (GridColumn col in this._gridEx.GridView.Columns) { if (col.Tag is GridColumnModel) { GridColumnModel model = col.Tag as GridColumnModel; if (model != null && !this.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.LabAutoGridValue || 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 = Regex.Replace(sqlValue, "#[^##]+#", " 1=1 "); LookupParentKey.Add(model.FieldName, m.Value.Replace("#", "")); } } this.ValueGridColumnTable.Add(model, BaseImpl.GetDataTableResult(sqlValue)); if (model.FieldType == ControlType.LabTreeType) { _treeColumnName = model.FieldName; } } if (model.FieldType == ControlType.LabCheckBox) { _checkColumns.Add(col.FieldName.ToLower()); } } } } } /// /// 获取导入到下拉框里的显示值 /// /// /// /// /// string GetValueByImportText(DataRow row, string fieldName, string text) { string value = text; foreach (GridColumnModel model in this.ValueGridColumnTable.Keys) { if (model.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase)) { string selWhere = "1=1"; DataTable table = this.ValueGridColumnTable[model]; if (model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabMultiSelectValueParam) { string[] splitString = text.Split(','); string nemValue = string.Empty; foreach (string newText in splitString) { if (table != null && table.Rows.Count > 0) { DataRow rowItemValue = table.Rows.Cast().FirstOrDefault(x => x[model.TextMember] + "" == newText); DataRow rowItemText = table.Rows.Cast().FirstOrDefault(x => x[model.ValueMember] + "" == newText); value = rowItemValue != null ? rowItemValue[model.ValueMember] + "" : rowItemText != null ? rowItemText[model.ValueMember] + "" : ""; } else { value = ""; } nemValue += value + ','; } value = nemValue.TrimEnd(','); } else { 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[model.ValueMember] + "" : rowItemText != null ? rowItemText[model.ValueMember] + "" : ""; } else value = ""; } } } return value; } private void SaveGridByAdapter() { string rowNum = "0"; string colNum = "0"; string colName = ""; bool keyIsNull = false; success = failed = 0; DataTable dt = (DataTable)gcMain.gridControl.DataSource; if (dt == null) { MessageBox.Show("请先读取Excel文件数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (dt.Rows.Count < 1) { MessageBox.Show("没有任何数据可以进行导入", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //提交到数据库 try { GridColumn primKeyColumn = gcMain.GridView.Columns.Where(n => n.FieldName.Equals(_primkey, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); string sql = "select * from " + _tableName + " 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 (!dt.Columns.Contains(item)) dt.Columns.Add(item); } } failedData = dt.Clone(); if (!failedData.Columns.Contains("import_errormsg")) failedData.Columns.Add("import_errormsg"); if (!failedData.Columns.Contains(this._importFlag)) failedData.Columns.Add(this._importFlag); for (int i = 0; i < dt.Rows.Count; i++) { dt.Rows[i][_importFlag] = "1"; if (ImportReturnName.Count > 0) { for (int j = 0; j < ImportReturnName.Count; j++) { string name = ImportReturnName[j]; string Value = ImportReturnValue[j]; dt.Rows[i][name] = Value; } } } //所有导入的主键集合 List parmaryKeys = new List(); //根据全表字段类型进行默认填充 int currRow = 0; foreach (DataRow dr in dt.Rows) { if (this.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 gcMain.GridView.VisibleColumns) { if (_calcFields.IndexOf(gc.FieldName) != -1) continue; //2022-8-2取消 原因:下方会处理关联,不用跳过 //if (gc.FieldName.Equals(_qzKey + _leftField)) // continue; if (datatb.Columns.Contains(gc.FieldName) && dt.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 = gcMain.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); //if (mainKeyField != "") // tmpRow[mainKeyField] = mainKeyValue; //if (!string.IsNullOrEmpty(this._primkey)) //{ // if (datatb.Columns.Contains(_primkey) && !string.IsNullOrWhiteSpace(_keyvalue)) // { // if (string.IsNullOrEmpty(tmpRow[_primkey] + "") || (tmpRow[_keyvalue] + "").Equals("0")) // { // tmpRow[_primkey] = _keyvalue; // } // } //} if (primKeyColumn != null) { if (!datatb.Columns.Contains(primKeyColumn.FieldName)) { datatb.Columns.Add(primKeyColumn.FieldName); } if (datatb.Columns.Contains(primKeyColumn.FieldName) && !string.IsNullOrWhiteSpace(primKeyColumn.FieldName)) { if (string.IsNullOrEmpty(tmpRow[primKeyColumn.FieldName] + "") || (tmpRow[primKeyColumn.FieldName] + "").Equals("0")) { tmpRow[primKeyColumn.FieldName] = _keyvalue; } } } //if (this.concatenatedPrefix) //{ // if (datatb.Columns.Contains(_qzKey + _leftField) && !string.IsNullOrWhiteSpace(_leftValue) && SysModel.AssociationLeft) // { // if (string.IsNullOrEmpty(tmpRow[_qzKey + _leftField] + "") || (tmpRow[_qzKey + _leftField] + "").Equals("0")) // { // tmpRow[_qzKey + _leftField] = _leftValue; // } // } //} //else //{ // if (datatb.Columns.Contains(_leftField) && !string.IsNullOrWhiteSpace(_leftValue) && SysModel.AssociationLeft) // { // if (string.IsNullOrEmpty(tmpRow[_qzKey + _leftField] + "") || (tmpRow[_qzKey + _leftField] + "").Equals("0")) // { // tmpRow[_qzKey + _leftField] = _leftValue; // } // } //} foreach (GridColumn gc in gcMain.GridView.VisibleColumns) { 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; } } } } 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++; } dt.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'", this._tableName, this._importFlag); SqlHelper.ExecuteNonQuery(sqlValue2); } string sqlValue = string.Format("update {0} set {1}='0' ", this._tableName, this._importFlag); sqlValue = string.Format("update {0} set {1}='0' where {1}!='0' ", this._tableName, this._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(); dt.Clear(); if (failed > 0) gcMain.gridControl.DataSource = failedData; LogUtil.WriteDebug(_menuCode, "导入数据", SysModel.MenuText, "数据导入,成功" + success.ToString() + "条,失败" + failed.ToString() + "条"); bool isUpload = UploadFileToAudit(FilePath, Model.keyvalue, Model.speciesNo, out string msg, out string fileId); if (!isUpload) { MessageUtil.Show($"附件上传失败\r\n{msg}"); } } catch (Exception ex) { string mesage = ex.Message; string sqlValue = string.Format("delete from {0} where {1}='1'", this._tableName, this._importFlag); SqlHelper.ExecuteNonQuery(sqlValue); foreach (GridColumn gc in gcMain.GridView.VisibleColumns) { 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); } } /// /// 数字转换时间格式 /// /// 数字,如:42095.7069444444/0.650694444444444 /// 日期/时间格式 private 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; } /// /// 查找当前是否存在指定值 /// /// /// /// private void setDefaultValue(DataTable dtTable, DataRow currentRow) { 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; /* foreach (DataColumn col in dtTable.Columns) { if (string.IsNullOrEmpty(currentRow[col.ColumnName] + "") || currentRow[col.ColumnName] + "" == "0") { if (col.ColumnName.Contains(columnPrefix + "operatorid")) currentRow[col.ColumnName] = OperatorId; if (col.ColumnName.Contains(columnPrefix+"operatorname")) currentRow[col.ColumnName] = OperatorName; if (col.ColumnName.Contains(columnPrefix+"operatedate")) currentRow[col.ColumnName] = DateTime.Now; } } */ } /// /// 说明:读取Excel /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. private void OnReadButtonClick(object sender, EventArgs e) { try { if (BaseImpl.HasExistsTable("P_SpecialImportTab")) { string searchSql = string.Format("select * from P_SpecialImportTab where moduleId = '{0}' and rightMenuName = '{1}'", Model.ModuleCode, Model.UnionModelCode); DataTable dataTable = SqlHelper.ExecuteDataTable(searchSql); if (dataTable == null || dataTable.Rows.Count == 0) { MessageUtil.Show("未配置关联\r\n请联系管理员进行配置"); return; } } else { MessageUtil.Show("未配置关联\r\n请联系管理员进行配置"); return; } 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 result = dialog.ShowDialog(); DataTable gcData = new DataTable(); if (result == DialogResult.OK) { //this.btnImport.Enabled = true; FilePath = dialog.FileName; try { using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { // 文件成功打开,说明没被占用 } } catch (Exception ex) { if (ex.Message.Contains("正由另一进程使用")) { MessageUtil.Show(ex.Message); return; } else { throw; } } string colFields = this.gcMain.GridView.Columns.ToString(','); //this.gcMain.GridControl.DataSource = this._gridEx.GridView.ToExcelDataTable(fileName, colFields); //bool isMultipleHeader = false; //if (this._gridEx is BandedGridControlEx) isMultipleHeader = true; //this.gcMain.GridView.Tag = isMultipleHeader; gcData = ToExcelDataTable(FilePath, out int count, out int errorCount, true); //设置默认值 if (SystemInfo.Instance.ImportDefaultValue) { foreach (GridColumn col in gcMain.GridView.VisibleColumns) { if (!gcData.Columns.Contains(col.FieldName)) gcData.Columns.Add(col.FieldName); } foreach (DataRow rowItem in gcData.Rows) { foreach (GridColumn col in gcMain.GridView.VisibleColumns) { // 未包含字段,则使用控件默认值. 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 (this.ParentGridEx != null) { DataRow SelectTheLine = this.ParentGridEx.GetViewFocusedDataRow(); fieldValue = ReplaceHelper.ReplaceRowParam(SelectTheLine, fieldValue); } fieldValue = BaseImpl.GetDefaultValue(fieldValue); if (!string.IsNullOrEmpty(fieldValue)) { rowItem[col.FieldName] = fieldValue; if (!string.IsNullOrEmpty(model.UnionFields)) { this.SetUnionValue(model, rowItem[col.FieldName] + "", rowItem); } } } } } } this.gcMain.GridControl.DataSource = gcData; //if (gcData.Rows.Count > 0 && gcData.Columns.Contains(_parmaryKey)) //{ // string ids = string.Empty; // foreach (DataRow dr in gcData.Rows) // { // ids += "'" + dr[_parmaryKey] + "'" + ","; // } // ids = ids.TrimEnd(','); // //if (ids) // this.btnCover.Visible = BaseImpl.GetIsContainKey(_tableName, _parmaryKey, ids); // this.btnImport.Enabled = !this.btnCover.Visible; //} } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:导入Excel /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. private void OnImportButtonClick(object sender, EventArgs e) { try { DataTable table = this.gcMain.GridControl.DataSourceTable(); if (table != null && table.Rows.Count > 0) { if (MessageUtil.Show("如果导入数据量太多将花费较长时间,是否确认导入", MessageBoxButtons.YesNo) != DialogResult.Yes) return; this._isImported = true; if (!this.DetermineImportConditions()) { return; } // 采用Adapter提交数据 this.SaveGridByAdapter(); // 采用存储过程保存 //this.SaveImportData(table); } else { MessageUtil.Show(ResourceKeys.NotFountGridData); } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2017-11-15 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. private void OnImportFormClosing(object sender, FormClosingEventArgs e) { try { this.DialogResult = this._isImported ? DialogResult.OK : DialogResult.Cancel; } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 设计关联 /// /// /// private void OnBtnCoverClick(object sender, EventArgs e) { FrmMain frmMain = new FrmMain(); frmMain.Model = Model; frmMain.ShowDialog(); } /// /// 判断导入条件 /// /// private bool DetermineImportConditions() { try { if (!string.IsNullOrEmpty(SysModel.ImportConditions)) { List ErrorLine = new List(); DataTable dt = (DataTable)gcMain.gridControl.DataSource; int currRow = 0; foreach (DataRow dr in dt.Rows) { currRow++; string cond = ReplaceHelper.ReplaceRowParam(dr, SysModel.ImportConditions); if (this.ParentGridEx != null) { DataRow SelectTheLine = this.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; } } return true; } catch (Exception ex) { XtraMessageBox.Show("条件判断错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } } /// /// 说明:计算列关联字段 /// 创建人:龚宇超 /// 创建日期:2017-12-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// The field value. private 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); } } } /// /// 获取表格数据 /// /// /// /// /// public DataTable ExcelToDatatable(string fileName, DynamicBomImportNew Model, string sheetName = "", int firstRowIndex = 0) { DataTable data = new DataTable(); FileStream fs; IWorkbook workbook = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 { workbook = new XSSFWorkbook(fs); } else if (fileName.IndexOf(".xls") > 0) // 2003版本 { workbook = new HSSFWorkbook(fs); } ISheet sheet; if (!string.IsNullOrEmpty(sheetName)) { sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据 } else { //也可以根据sheet编号来获取数据 sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表) } if (sheet != null) { int startRow = firstRowIndex + 1; IRow firstRow = sheet.GetRow(firstRowIndex); IRow bandRow = null; int cellCount = firstRow.LastCellNum; for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)//第一行列数循环 { ICell titleCell = firstRow.GetCell(i); ICell bandCell = null; bool isBandTitle = false; if (titleCell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, firstRowIndex, i); startRow = mergrRange.LastRow + 1; if (mergrRange != null) { if (mergrRange.FirstColumn < mergrRange.LastColumn && false)//&& !Model.CustomerServiceApp { isBandTitle = true; bandRow = sheet.GetRow(mergrRange.LastRow + 1); titleCell = firstRow.GetCell(mergrRange.FirstColumn); bandCell = bandRow.GetCell(i); CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i); if (bandMergrRange != null) { startRow = bandMergrRange.LastRow + 1; } else { startRow = mergrRange.LastRow + 2; } } else { startRow = mergrRange.LastRow + 1; } } } string fieldName = ""; if (!isBandTitle || bandRow == null) { fieldName = GetCellValue(titleCell); } else { fieldName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}"; } if (string.IsNullOrEmpty(fieldName) && titleCell.IsMergedCell) { cellCount -= 1; continue; } DataColumn column = new DataColumn(fieldName);//获取标题 data.Columns.Add(column);//添加列 } //最后一行的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; i++)//循环遍历所有行 { IRow row = sheet.GetRow(i);//第几行 if (row == null) { continue; //没有数据的行默认是null; } //将excel表每一行的数据添加到datatable的行中 DataRow dataRow = data.NewRow(); int dataRowIndex = 0; for (int j = firstRow.FirstCellNum; j < cellCount; j++) { ICell cell = row.GetCell(j); if (cell != null && cell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, i, j); if (j == mergrRange.FirstColumn) { dataRow[dataRowIndex] = GetCellValue(row.GetCell(j)); dataRowIndex += 1; } else { continue; } } else { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null { dataRow[dataRowIndex] = GetCellValue(row.GetCell(j)); dataRowIndex += 1; } } } data.Rows.Add(dataRow); } } return data; } catch (IOException ex) { throw new IOException(string.Format("读取模板内容失败,原因:{0}", ex.Message)); } catch (Exception ex) { throw new Exception(string.Format("读取模板内容失败,原因:{0}", ex.Message)); } } /// /// 获取合并区域 /// /// /// /// /// private CellRangeAddress FindMergedRegion(ISheet sheet, int rowIndex, int columnIndex) { int mergedRegionsCount = sheet.NumMergedRegions; for (int i = 0; i < mergedRegionsCount; i++) { CellRangeAddress mergedRegion = sheet.GetMergedRegion(i); if (mergedRegion.IsInRange(rowIndex, columnIndex)) { return mergedRegion; // 返回合并区域 } } return null; // 未找到合并区域 } /// /// 获取单元格值 /// /// /// public static string GetCellValue(ICell cell) { string cellValue = ""; try { if (cell != null) { // 根据单元格类型获取值 switch (cell.CellType) { case CellType.String: cellValue = cell.StringCellValue; break; case CellType.Numeric: cellValue = cell.NumericCellValue.ToString(); break; case CellType.Boolean: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.Formula://单元格中带有公式,根据类型继续判断 switch (cell.CachedFormulaResultType) { case CellType.String: cellValue = cell.StringCellValue; break; case CellType.Numeric: cellValue = cell.NumericCellValue.ToString(); break; case CellType.Boolean: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.Blank: break; default: cellValue.ToString(); break; } break; default: cellValue = cell.ToString(); break; } } } catch (Exception) { } return cellValue; } /// /// 导入到表格中 /// /// /// /// /// /// public DataTable ToExcelDataTable(string fileName, out int count, out int errorCount, bool isDirectImport = false) { count = 0; errorCount = 0; GridView gridView = gcMain.GridView; GridColumn primKeyColumn = gcMain.GridView.Columns.Where(n => n.FieldName.Equals(_primkey, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); DataTable columnsTable = new DataTable(); string searchSql = string.Format("select * from P_SpecialImportTab where moduleId = '{0}' and rightMenuName = '{1}'", Model.ModuleCode, Model.UnionModelCode); DataTable dataTable = SqlHelper.ExecuteDataTable(searchSql); if (dataTable != null && dataTable.Rows.Count > 0) { DataRow dataRow = dataTable.Rows[0]; string unionColumn = dataRow["Ls_UnionColumn"] + ""; List unionColumnList = unionColumn.Split(',').ToList(); columnsTable = GetSourceTable(unionColumnList); } DataTable table = gridView.GridControl.DataSourceTable(); DataTable sourceDataTable = ExcelToDatatable(fileName, Model, "", FirstRowIndex); DataView filterDataView = new DataView(sourceDataTable); try { //if (!string.IsNullOrEmpty(Model.ReadTableCond)) //{ // filterDataView.RowFilter = Model.ReadTableCond; //} } catch (Exception) { } List dataRows = columnsTable.Rows.Cast().Where(n => !string.IsNullOrEmpty(n["excelFieldName"] + "") && !string.IsNullOrEmpty(n["clientFieldName"] + "")).ToList(); int index = gridView is BandedGridView ? FirstRowIndex + 1 : FirstRowIndex; 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 firstRow = sheet.GetRow(index); IRow bandRow = null; int startRow = FirstRowIndex + 1; string bandTitel = string.Empty; ColumnList.Clear(); int cellCount = firstRow.LastCellNum; // 添加列 for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++) { ICell titleCell = firstRow.GetCell(i); ICell bandCell = null; bool isBandTitle = false; if (titleCell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, index, i); startRow = mergrRange.LastRow + 1; if (mergrRange != null) { if (mergrRange.FirstColumn < mergrRange.LastColumn && false)//&& !Model.CustomerServiceApp { isBandTitle = true; bandRow = sheet.GetRow(mergrRange.LastRow + 1); titleCell = firstRow.GetCell(mergrRange.FirstColumn); bandCell = bandRow.GetCell(i); CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i); if (bandMergrRange != null) { startRow = bandMergrRange.LastRow + 1; } else { startRow = mergrRange.LastRow + 2; } } else { startRow = mergrRange.LastRow + 1; } } } string headerName = ""; if (!isBandTitle || bandRow == null) { headerName = GetCellValue(titleCell); } else if (!string.IsNullOrEmpty(GetCellValue(bandCell))) { headerName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}"; } if (string.IsNullOrEmpty(headerName)) { cellCount -= 1; continue; } DataRow row = columnsTable.Rows.Cast().Where(x => (x["excelFieldName"] + "").Equals(headerName)).FirstOrDefault(); headerName = row != null ? row["clientFieldName"] + "" : headerName; if (string.IsNullOrWhiteSpace(headerName)) { continue; } GridColumn col = gridView.Columns.OfType().FirstOrDefault(x => x.FieldName.Equals(headerName)); if (col != null) { if (!table.Columns.Contains(col.FieldName)) { table.Columns.Add(col.FieldName, col.ColumnType); } ColumnList.Add(col.Tag as GridColumnModel); } else { MessageUtil.Show("未找到列->" + headerName + ""); } } InitializeValueGrid(); bool AutoImportCal = SystemInfo.Instance.AutoImportCal;//是否执行计算公式 bool isBreak = false; for (int i = startRow; i <= sheet.LastRowNum; i++) { ToAssignment = true; CurrentRow = i; DataRow rowSource = sourceDataTable.Rows[i - startRow]; if (!filterDataView.Cast().Any(rowView => rowView.Row == rowSource)) { continue; } 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; for (int j = row.FirstCellNum; j < firstRow.LastCellNum; j++) { CurrentColumn = j; ICell cell = row.GetCell(j); ICell titleCell = firstRow.GetCell(j); ICell bandCell = null; bool isBandTitle = false; if (titleCell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, index, j); startRow = mergrRange.LastRow + 1; if (mergrRange != null) { if (mergrRange.FirstColumn < mergrRange.LastColumn && false)//&& !Model.CustomerServiceApp { isBandTitle = true; bandRow = sheet.GetRow(mergrRange.LastRow + 1); titleCell = firstRow.GetCell(mergrRange.FirstColumn); bandCell = bandRow.GetCell(j); CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, j); if (bandMergrRange != null) { startRow = bandMergrRange.LastRow + 1; } else { startRow = mergrRange.LastRow + 2; } } else { startRow = mergrRange.LastRow + 1; } } } if (!isBandTitle || bandRow == null) { columnName = GetCellValue(titleCell); } else if (!string.IsNullOrEmpty(GetCellValue(bandCell))) { columnName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}"; } if (string.IsNullOrEmpty(columnName)) { continue; } DataRow colDataRow = dataRows.Where(n => (n["excelFieldName"] + "").Equals(columnName)).FirstOrDefault(); if (colDataRow == null) { continue; } columnName = colDataRow["clientFieldName"] + ""; //if (!bandTitel.Equals(Bandcell + "") && !string.IsNullOrEmpty(Bandcell + "")) bandTitel = Bandcell + ""; col = gridView.Columns.OfType().FirstOrDefault(x => x.FieldName.Equals(columnName)); if (col == null) continue; GridColumnModel model = col.Tag as GridColumnModel; if (cell != null) { try { if (cell.CellType == CellType.Blank) { continue; } if (cell.CellType == CellType.Numeric && (cell + "").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.LabMultiSelectValueParam || model.FieldType == ControlType.LabTreeLookValue )) { bool isEmpty = model.CanNull; string fieldValue = GetValueByImportText(dataRow, col.FieldName, cell + ""); if ((model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueParam) && GetCellValue(cell).Contains(",")) { string[] cellText = GetCellValue(cell).Split(','); foreach (string cellValue in cellText) { fieldValue += GetValueByImportText(dataRow, col.FieldName, cellValue) + ','; } 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 { 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] = GetCellValue(cell); if (AutoImportCal) { if (!string.IsNullOrEmpty(model.UnionFields)) { SetUnionValue(model, dataRow[col.FieldName] + "", dataRow); } SetCalcValue(model, dataRow[col.FieldName] + "", dataRow); } } } } } catch (Exception) { throw; } } if (ReplaceHelper.ReplaceRowParamCond(dataRow, Model.endRowHand.Replace(colDataRow["excelFieldName"] + "", columnName))) { isBreak = true; break; } } if (isBreak) { break; } if (primKeyColumn != null) { if (!table.Columns.Contains(primKeyColumn.FieldName)) { table.Columns.Add(primKeyColumn.FieldName); } if (table.Columns.Contains(primKeyColumn.FieldName) && !string.IsNullOrWhiteSpace(primKeyColumn.FieldName)) { if (string.IsNullOrEmpty(dataRow[primKeyColumn.FieldName] + "") || (dataRow[primKeyColumn.FieldName] + "").Equals("0")) { dataRow[primKeyColumn.FieldName] = _keyvalue; } } } table.Rows.Add(dataRow); count += 1; } 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(); } /// /// 计算列计算公式 /// /// /// /// private void SetCalcValue(GridColumnModel model, string fieldValue, DataRow rowItem) { try { if (rowItem != null && model != null) { foreach (GridColumn col in this.ParentView.Columns) { GridColumnModel colModel = col.Tag as GridColumnModel; if (colModel == null) continue; string defultValue = colModel.DefaultValue; if (colModel.FieldType == 7 && rowItem.Table.Columns.Contains(col.FieldName) && string.IsNullOrEmpty(rowItem[col.FieldName] + "") && !string.IsNullOrEmpty(colModel.DefaultValue)) { defultValue = ReplaceHelper.ReplaceUserInfo(colModel.DefaultValue); if (defultValue.StartsWith("@")) { defultValue = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, defultValue)); } if (IsNumberic(defultValue)) rowItem[col.FieldName] = defultValue;//colModel.DefaultValue; } } 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 { string result = string.Empty; if (calcExpr.StartsWith("@")) { result = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, calcExpr)); } else { calcExpr = ReplaceHelper.ReplaceRowParam(rowItem, 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 { //计算后先执行保存小数位数 if (SystemInfo.Instance.ComputeFormatting) 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)) { this.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) { Console.WriteLine(ex.Message); } } /// /// 判断输入的字符串是否可以转换成数值类型 /// /// /// public static bool IsNumberic(string str) { double vsNum; bool isNum; isNum = double.TryParse(str, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out vsNum); return isNum; } /// /// 获取数据源 /// /// private DataTable GetSourceTable(DataTable dataTable) { DataTable sourceTable = new DataTable(); sourceTable.Columns.Add("excelFieldName"); sourceTable.Columns.Add("clientFieldName"); if (dataTable != null) { foreach (DataColumn col in dataTable.Columns) { DataRow dataRow = sourceTable.NewRow(); dataRow["excelFieldName"] = col.ColumnName; sourceTable.Rows.Add(dataRow); } } return sourceTable; } /// /// 获取数据源 /// /// private DataTable GetSourceTable(List unionColumnList) { DataTable sourceTable = new DataTable(); sourceTable.Columns.Add("excelFieldName"); sourceTable.Columns.Add("clientFieldName"); if (unionColumnList != null) { foreach (string unionColumn in unionColumnList) { string[] unionCilumnArray = unionColumn.Split('^'); if (unionCilumnArray.Length == 2) { DataRow dataRow = sourceTable.NewRow(); dataRow["excelFieldName"] = unionCilumnArray[0]; dataRow["clientFieldName"] = unionCilumnArray[1]; sourceTable.Rows.Add(dataRow); } } } return sourceTable; } /// /// 上传文件 /// /// /// /// /// /// /// private bool UploadFileToAudit(string filePath, string idValue, string speciesno, out string msg, out string outFileId) { bool isUpload = false; string File = filePath; string returnMsg = ""; string fileId = ""; string postUrl = ""; try { //获取文件信息 FileInfo fileInfo = new FileInfo(File); string suffix = Path.GetExtension(File); string name = fileInfo.Name; DateTime creationTime = fileInfo.CreationTime; byte[] fileBytes = ConvertFileToBytes(File); string fileStream = Convert.ToBase64String(fileBytes); string userId = ERPInfo.Instance.UserId; DateTime uploadTime = DateTime.Now; //上传文件到服务器目录 postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}&confirm=1"; if (!string.IsNullOrEmpty(idValue)) { string token = ""; string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx"; HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8); Dictionary loginPmsDic = new Dictionary(); loginPmsDic.Add("method", "Login"); loginPmsDic.Add("username", HttpUtility.UrlEncode(ERPInfo.Instance.UserName)); loginPmsDic.Add("password", HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord)); HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult); if (loginResponse != null && !string.IsNullOrEmpty(loginResult)) { JObject jObject = JsonConvert.DeserializeObject(loginResult); if (jObject.ContainsKey("success")) { if ((jObject["success"] + "").Equals("True")) { if (jObject.ContainsKey("token")) { token = jObject["token"] + ""; } } } } if (!string.IsNullOrEmpty(token)) { postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, Model.UnionModelCode, HttpUtility.UrlEncode(idValue), "file", fileBytes.Length, 0, HttpUtility.UrlEncode(name), "DoWebUpload", speciesno); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; Dictionary headerDic = new Dictionary(); headerDic.Add("Authorization", $"Bearer {token}"); HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { if (jsonObject.ContainsKey("other")) { fileId = jsonObject["other"] + ""; //BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 2 where fileid = '{fileId}'"); } isUpload = true; } else { if (jsonObject.ContainsKey("msg")) { returnMsg = jsonObject["msg"] + ""; } isUpload = false; } } else { returnMsg = "上传请求失败"; isUpload = false; } } else { returnMsg = loginResult; isUpload = false; } } else { returnMsg = "上传节点值不能为空"; isUpload = false; } } catch (Exception ex) { returnMsg = ex.Message; throw new Exception($"文件{Path.GetFileName(filePath)}上传失败\r\n{ex.Message}"); isUpload = false; } msg = retur