Files
lserp_cs_6.0/插件库/Lskj.Control/FrmCover.cs
T

1103 lines
51 KiB
C#

/******************************
* 说明:导入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 System.Data.Common;
namespace Lskj.Control
{
/// <summary>
/// 导入Excel
/// </summary>
public partial class FrmCover : BaseForm
{
public DataTable ReverseData;
/// <summary>
/// 导入至数据库中
/// </summary>
public bool ImportIntoDatabase=false;
/// <summary>
/// 导入至数据库中
/// </summary>
public string afterSql = string.Empty;
/// <summary>
/// 判断是否是导入后的数据
/// </summary>
private string _importFlag = "lskjimport_errorFlag";
/// <summary>
/// 是否导入过记录
/// </summary>
private bool _isImported;
/// <summary>
/// 表名
/// </summary>
private string _tableName;
/// <summary>
/// 模块编号
/// </summary>
private string _menuCode;
/// <summary>
/// 模块名称
/// </summary>
private string _fromText;
/// <summary>
/// 主键字段
/// </summary>
private string _parmaryKey;
private string _qzKey;
private string _treeColumnName;
private int success = 0, failed = 0;
private ModuleModel SysModel;
private List<string> _checkColumns;
private DataTable _tableColumns;
public Dictionary<GridColumnModel, DataTable> ValueGridColumnTable;
public Dictionary<string, string> LookupParentKey;
public List<string> _calcFields;
/// <summary>
/// 父容器表格
/// </summary>
public GridControlEx ParentGridEx;
/// <summary>
/// 导入返回控件名
/// </summary>
public List<string> ImportReturnName = new List<string>();
/// <summary>
/// 导入返回控件值
/// </summary>
public List<string> ImportReturnValue = new List<string>();
public FrmCover()
{
InitializeComponent();
}
public FrmCover(bool importIntoDatabase,string moduleCode,string primaryKey,string aftersql)
{
try
{
InitializeComponent();
this.ImportIntoDatabase = importIntoDatabase;
if (this.ImportIntoDatabase) this.btnCover.Text = "导入数据";
this.afterSql = aftersql;
DataRow modelRow = MainImpl.GetSystemdllTab(moduleCode);//获取模块信息
if (modelRow == null)
{
MessageUtil.Show("模块编号[" + moduleCode + "],配置错误!\r\n该模块信息未找到!");
return;
}
this.SysModel = new ModuleModel(modelRow);// 系统模块实体对象
this._tableColumns = BaseModuleImpl.GetBaseGridColumns(this.SysModel.ModeCode);
this._tableName = this.SysModel.MenuTable;
this._menuCode = this.SysModel.ModeCode;
this._parmaryKey = primaryKey;
this._qzKey = this.SysModel.PrefixKey;
this._calcFields = new List<string>();
this._fromText = this.SysModel.MenuText;
bool isAdmin = ERPInfo.Instance.UserName.Equals("管理员");
//this.btnCover.Visible = SysModel == null ? isAdmin : isAdmin ? true : SysModel.OperPermissionsUser.Contains(ERPInfo.Instance.UserName);
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);
}
Lskj.Control.Model.AutoSizeChange.ControllInitializeSize(this);
}
/// <summary>
/// <para>说明:初始化GridControl</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
private void InitializeGrid()
{
this.gcMain.GridView.Columns.Clear();
if (this.SysModel.AutoMultiHeader == 1 && this._tableColumns != null && this._tableColumns.Rows.Count > 0)
{
//多表头
this.gcMain = new BandedGridControlEx();
(this.gcMain as BandedGridControlEx).moduleModel = this.SysModel;
this.gcMain.Dock = DockStyle.Fill;
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<GridColumnModel, DataTable>();
this._checkColumns = new List<string>();
this.LookupParentKey = new Dictionary<string, string>();
foreach (GridColumn col in this.gcMain.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 ||
(model.FieldType == ControlType.LabSelectReturnIdNew && model.ModuleFrameDisplayText) ||
model.FieldType == ControlType.LabModuleAddRowsID
)
{
string sqlValue = model.SqlSource;
if (model.FieldType == ControlType.LabSelectReturnId || (model.FieldType == ControlType.LabSelectReturnIdNew && model.ModuleFrameDisplayText) || model.FieldType == ControlType.LabModuleAddRowsID)
{
if ((model.IsRadio && !string.IsNullOrWhiteSpace(model.addModuleld)) || model.FieldType == ControlType.LabSelectReturnIdNew || model.FieldType == ControlType.LabModuleAddRowsID)
{
//单选模式数据源为模块sql 新版模块选中返回id固定位模块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());
}
}
}
}
}
public 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
|| (model.FieldType == ControlType.LabSelectReturnId && !model.IsRadio)
|| (model.FieldType == ControlType.LabSelectReturnIdNew && !model.IsRadio && model.ModuleFrameDisplayText))
{
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<DataRow>().FirstOrDefault(x => x[model.TextMember] + "" == newText);
DataRow rowItemText = table.Rows.Cast<DataRow>().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<DataRow>().FirstOrDefault(x => x[model.TextMember] + "" == text);
DataRow rowItemText = table.Rows.Cast<DataRow>().FirstOrDefault(x => x[model.ValueMember] + "" == text);
value = rowItemValue != null ? rowItemValue[model.ValueMember] + "" : rowItemText != null ? rowItemText[model.ValueMember] + "" : "";
}
else
value = "";
}
}
}
return value;
}
private bool 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 false;
}
if (dt.Rows.Count < 1)
{
MessageBox.Show("没有任何数据可以进行导入", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
//提交到数据库
try
{
string sql = "select * from " + _tableName + " where 1<>1";
DbDataAdapter dat = BaseImpl.GetAdapterResult(sql);
DbCommandBuilder scb = SqlHelper.dbFactory.CreateCommandBuilder();
scb.DataAdapter = dat;
//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<string> parmaryKeys = new List<string>();
//根据全表字段类型进行默认填充
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 ||
(model.FieldType == ControlType.LabSelectReturnIdNew && model.ModuleFrameDisplayText)||
model.FieldType == ControlType.LabModuleAddRowsID
))
{
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;
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 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++;
}
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);
return false;
}
if (!string.IsNullOrWhiteSpace(this.afterSql))
{
try
{
string pattern = @"(\w+)\((.*?)\)";
Regex regex = new Regex(pattern);
Match match = regex.Match(afterSql);
if (match.Success)
{
string functionName = match.Groups[1].Value;
string parameters = match.Groups[2].Value;
if (!string.IsNullOrEmpty(functionName))
{
DataTable sqlParametersTab = BaseImpl.GetDataTableResult($"SELECT PARAMETER_NAME,PARAMETER_MODE,CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.PARAMETERS WHERE SPECIFIC_NAME = '{functionName}' ORDER BY ORDINAL_POSITION;");
string[] parametersArray = parameters.Split(',');
List<SqlParameter> sqlParameters = new List<SqlParameter>();
foreach (DataRow parameterRow in sqlParametersTab.Rows)
{
string parameterName = parameterRow["PARAMETER_NAME"] + "";
string parameterMode = parameterRow["PARAMETER_MODE"] + "";
int.TryParse(parameterRow["CHARACTER_MAXIMUM_LENGTH"] + "", out int dataLength);
string dataType = parameterRow["DATA_TYPE"] + "";
SqlParameter sqlParameter = null;
if (parameterMode.Equals("int"))
{
sqlParameter = new SqlParameter(parameterName, SqlDbType.Int);
}
else
{
sqlParameter = new SqlParameter(parameterName, SqlDbType.VarChar, dataLength);
}
if (parameterMode.Equals("IN"))
{
sqlParameter.Direction = ParameterDirection.Input;
}
else
{
sqlParameter.Direction = ParameterDirection.Output;
}
sqlParameters.Add(sqlParameter);
}
for (int i = 0; i < sqlParameters.Count; i++)
{
SqlParameter sqlParameter = sqlParameters[i];
if (parametersArray.Length > i)
{
string commandParameter = parametersArray[i];
string field = commandParameter.Replace("@", "").Replace("{", "").Replace("}", "");
//string value = focusedRow.Table.Columns.Contains(field) ? focusedRow[field] + "" : commandParameter.Replace("@", "");
//value = SearchObj.ReplaceControlValue(value);
//value = TopControlObj.ReplaceControlValue(value);
//value = ReplaceControlValue(value, MainControlPanel);
//value = value.Replace("@", "").Replace("{", "").Replace("}", "");
//sqlParameter.Value = value;
sqlParameter.Value = field;
}
}
SqlParameter returnValue = new SqlParameter("@return", SqlDbType.Int, 4);
returnValue.Direction = ParameterDirection.ReturnValue;
sqlParameters.Add(returnValue);
SqlHelper.ExecuteNonQuery(CommandType.StoredProcedure, functionName, sqlParameters.ToArray());
if (!(returnValue.Value + "").Equals("1"))
{
SqlParameter outSqlParameter = sqlParameters.Cast<SqlParameter>().Where(n => n.Direction == ParameterDirection.Output).FirstOrDefault();
string msg = "导入后执行sql失败";
if (outSqlParameter != null)
{
string outMessage = outSqlParameter.Value + "";
if (!string.IsNullOrEmpty(outMessage))
{
msg="导入后执行sql失败:" + outSqlParameter.Value + "";
}
}
MessageUtil.Show(msg);
string deleteSql = string.Format("delete from {0} where {1}='1'", this._tableName, this._importFlag);
SqlHelper.ExecuteNonQuery(deleteSql);
return false;
}
}
else
{
string deleteSql = string.Format("delete from {0} where {1}='1'", this._tableName, this._importFlag);
SqlHelper.ExecuteNonQuery(deleteSql);
MessageUtil.Show("导入后执行sql配置错误");
}
}
else
{
string deleteSql = string.Format("delete from {0} where {1}='1'", this._tableName, this._importFlag);
SqlHelper.ExecuteNonQuery(deleteSql);
MessageUtil.Show("导入后执行sql配置错误");
}
}
catch (Exception e)
{
string deleteSql = string.Format("delete from {0} where {1}='1'", this._tableName, this._importFlag);
SqlHelper.ExecuteNonQuery(deleteSql);
MessageUtil.Show("导入后执行sql执行失败" + e.Message);
}
}
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);
//if (!string.IsNullOrWhiteSpace(SysModel.afterimportSql2) && failed == 0 && datatb.Rows.Count > 0)
//{
// try
// {
// DataRow dataRow = datatb.Rows[0];
// SqlHelper.ExecuteNonQuery(ReplaceHelper.ReplaceRowParam(dataRow, ReplaceHelper.ReplaceUserInfo(SysModel.afterimportSql2)));
// }
// catch (Exception e)
// {
// MessageUtil.Show("导入后执行sql执行失败" + e.Message);
// }
//}
datatb.Clear();
dt.Clear();
if (failed > 0)
gcMain.gridControl.DataSource = failedData;
LogUtil.WriteDebug(_menuCode, "导入数据", SysModel.MenuText, "数据导入,成功" + success.ToString() + "条,失败" + failed.ToString() + "条");
return true;
}
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);
return false;
}
}
/// <summary>
/// 数字转换时间格式
/// </summary>
/// <param name="timeStr">数字,如:42095.7069444444/0.650694444444444</param>
/// <returns>日期/时间格式</returns>
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;
}
/// <summary>
/// 查找当前是否存在指定值
/// </summary>
/// <param name="dtTable"></param>
/// <param name="currentRow"></param>
/// <param name="key"></param>
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;
}
}
*/
}
/// <summary>
/// <para>说明:读取Excel</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void OnReadButtonClick(object sender, EventArgs e)
{
try
{
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;
string fileName = dialog.FileName;
string colFields = this.gcMain.GridView.Columns.ToString(',');
gcData = this.gcMain.GridView.ToExcelDataTable(fileName, colFields, 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;
}
}
catch (Exception ex)
{
string Message = ErrorMessage.PromptErrorMessage(ex);
MessageUtil.Show(Message, ex.Message);
}
}
/// <summary>
/// <para>说明:导入覆盖Excel</para>
/// <para>创建人:王一帆</para>
/// <para>创建日期:2021-04-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void OnCoverButtonClick(object sender, EventArgs e)
{
try
{
if (this.ImportIntoDatabase)
{
//导入数据添加到数据库中
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提交数据
bool result = this.SaveGridByAdapter();
if(result) this.DialogResult = DialogResult.OK;
}
else
{
MessageUtil.Show(ResourceKeys.NotFountGridData);
}
}
else
{
//导入数据返回外部
this.ReverseData = null;
if (MessageUtil.Show("注意!覆盖功能将替换原有的数据请慎重使用!是否确认覆盖?", MessageBoxButtons.YesNo) != DialogResult.Yes)
return;
List<string> ColumnNameList = GridExtend.ColumnNameList;
//string sql = "select * from " + _tableName + " where 1<>1";
//DbDataAdapter dat = BaseImpl.GetAdapterResult(sql);
//DataTable datatb = new DataTable();
//dat.Fill(datatb);
DataTable table = this.gcMain.GridControl.DataSourceTable();
if (table != null && table.Rows.Count > 0)
{
this.ReverseData = table;
this.DialogResult = DialogResult.OK;
}
else
{
MessageUtil.Show(ResourceKeys.NotFountGridData);
}
}
}
catch (Exception ex)
{
string Message = ErrorMessage.PromptErrorMessage(ex);
MessageUtil.Show(Message, ex.Message);
}
}
/// <summary>
/// 判断导入条件
/// </summary>
/// <returns></returns>
private bool DetermineImportConditions()
{
try
{
if (!string.IsNullOrEmpty(SysModel.ImportConditions))
{
List<int> ErrorLine = new List<int>();
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;
}
}
/// <summary>
/// <para>说明:计算列关联字段</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-12-18 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="model">The model.</param>
/// <param name="fieldValue">The field value.</param>
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);
}
}
}
}
}