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

1329 lines
63 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 System.Data.Common;
namespace Lskj.Control
{
/// <summary>
/// 导入Excel
/// </summary>
public partial class FrmImport : BaseForm
{
/// <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 _leftField, _leftValue;
private string _treeColumnName;
private int success = 0, failed = 0;
private ModuleModel SysModel;
private List<string> _checkColumns;
private DataTable _tableColumns;
/// <summary>
/// 拼接前缀
/// </summary>
private bool concatenatedPrefix;
/// <summary>
/// Occurs when [on import click].
/// </summary>
public event EventHandler OnImportClick;
public DataColumnCollection SourceColumns = null;
public Dictionary<GridColumnModel, DataTable> ValueGridColumnTable;
public Dictionary<string, string> LookupParentKey;
public List<string> _calcFields;
/// <summary>
/// 父容器表格
/// </summary>
public GridControlEx ParentGridEx;
/// <summary>
/// 父容器表格条件
/// </summary>
public MyControl SearchObj;
/// <summary>
/// 源表格
/// </summary>
private GridControlEx _gridEx;
/// <summary>
/// 导入返回控件名
/// </summary>
public List<string> ImportReturnName =new List<string>();
/// <summary>
/// 导入返回控件值
/// </summary>
public List<string> ImportReturnValue = new List<string>();
public FrmImport()
: this("", "", "", null, "", "", "", "")
{
}
public FrmImport(string tableName, string menuCode, string parmaryKey, GridControlEx gridEx, string qzKey, string leftField, string leftValue, string Fromtext, bool ConcatenatedPrefix = true)
{
try
{
InitializeComponent();
this._tableColumns = BaseModuleImpl.GetBaseGridColumns(menuCode);
this._tableName = tableName;
this._menuCode = menuCode;
this._parmaryKey = parmaryKey;
this._gridEx = gridEx;
this._qzKey = qzKey;
this._leftValue = leftValue;
this._leftField = leftField;
this._calcFields = new List<string>();
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);
}
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()
{
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
{
//foreach (GridColumn item in this._gridEx.GridView.VisibleColumns)
//{
// if (item.FieldName.Equals("RightMenuBtnEdit")) continue;
// GridColumn col = new GridColumn();
// col.Tag = item.Tag;
// col.FieldName = item.FieldName;
// col.Width = item.Width;
// col.Caption = item.Caption;
// col.Visible = true;
// if (this._gridEx is BandedGridControlEx)
// {
// GridColumnModel tag = item.Tag as GridColumnModel;
// if (tag.FieldText.Contains("|")) col.Caption = tag.FieldText;
// }
// //col.AppearanceCell.Options.UseFont = true;
// //col.AppearanceCell.Font = new Font("宋体", 14f);
// this.gcMain.GridView.Columns.Add(col);
//}
//this.gcMain.SetReadOnlyColumns(_tableColumns, GridCustomColumnStruct.BaseMainGridView + this.SysModel.FormKey);
//可编辑列可以触发关联,计算
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._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||
(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 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
{
WaitForm.ShowForm();
string sql = "select * from " + _tableName + " where 1<>1";
//SqlDataAdapter dat = BaseImpl.GetAdapterResult(sql);
//SqlCommandBuilder scb = new SqlCommandBuilder(dat);
DbDataAdapter dat = BaseImpl.GetAdapterResult(sql);
DbCommandBuilder scb = SqlHelper.dbFactory.CreateCommandBuilder();
scb.DataAdapter = 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;
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);
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() + "条");
}
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);
}
finally
{
WaitForm.HideForm();
}
}
/// <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>说明:保存导入的数据</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-11-15 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
private void SaveImportData(DataTable table)
{
if (table != null && table.Rows.Count > 0)
{
if (string.IsNullOrEmpty(this._tableName))
{
MessageUtil.Show(ResourceKeys.MenuTableNameIsNull);
return;
}
List<BaseSaveModel> mList = new List<BaseSaveModel>();
GridColumnCollection gridColumns = this._gridEx.GridView.Columns;
//DataColumnCollection columns = (this._gridEx.GridControl.DataSourceTable() as DataTable).Columns;
foreach (DataRow row in table.Rows)
{
string insertSql = "insert into {0}({1}) values({2});";
string insertFields = string.Empty;
string insertValues = string.Empty;
foreach (DataColumn col in SourceColumns)
{
//处理表中的计算列
if (_calcFields.IndexOf(col.ColumnName) != -1)
continue;
if (col.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase) || col.ColumnName.Equals(_qzKey + "id", StringComparison.OrdinalIgnoreCase))
continue;
if (col.ColumnName.EndsWith("operatorid", StringComparison.OrdinalIgnoreCase))
{
insertFields += col.ColumnName + ",";
insertValues += ERPInfo.Instance.UserId + ",";
}
else if (col.ColumnName.EndsWith("operatename", StringComparison.OrdinalIgnoreCase))
{
insertFields += col.ColumnName + ",";
insertValues += "'" + ERPInfo.Instance.UserName + "',";
}
else if (col.ColumnName.EndsWith("operatedate", StringComparison.OrdinalIgnoreCase))
{
insertFields += col.ColumnName + ",";
insertValues += "'" + DateTime.Now + "',"; ;
}
else
{
if (table.Columns.Contains(col.ColumnName))
{
string dataType = col.DataType.ToString().ToLower();
string fieldValue = GetValueByImportText(row, col.ColumnName, row[col.ColumnName] + "");
if (_checkColumns.IndexOf(col.ColumnName.ToLower()) != -1)
{
fieldValue = fieldValue.Equals("是") ? "1" : "0";
}
insertFields += col.ColumnName + ",";
insertValues += string.IsNullOrWhiteSpace(fieldValue) && (dataType.Contains("decimal") || dataType.Contains("datetime")) ? "NULL," : "N'" + fieldValue + "',";
}
else
{
if (!string.IsNullOrEmpty(_treeColumnName) && col.ColumnName.ToLower() == _treeColumnName.ToLower())
{
insertFields += col.ColumnName + ",";
insertValues += "N'" + _leftValue + "',";
}
}
}
}
insertFields = insertFields.TrimEnd(',');
insertValues = insertValues.TrimEnd(',');
mList.Add(new BaseSaveModel()
{
MenuCode = _menuCode,
TableName = _tableName,
KeyField = _parmaryKey,
FieldValue = row.Table.Columns.Contains(_parmaryKey) ? row[_parmaryKey] + "" : "",
BaseSaveType = SaveType.Add,
BaseSql = string.Format(insertSql, _tableName, insertFields, insertValues),
row = row
});
}
try
{
// 批量保存数据
if (BaseModuleImpl.SaveBaseGridData(mList))
{
table.Rows.Clear();
MessageUtil.Show(ResourceKeys.ImportSuccess);
}
else
{
int[] records = new int[mList.Count];
for (int i = 0; i < mList.Count; i++)
{
BaseSaveModel model = mList[i];
records[i] = Convert.ToInt32(model.Success);
if (!model.Success)
{
model.row["import_errormsg"] = model.FaultMsg;
LogHelper.Instance.WriteLog(model.FaultMsg + "(" + model.BaseSql + ")", ResourceKeys.ImportFault);
}
else
{
// 移除导入成功的数据行
if (table.Rows.IndexOf(model.row) != -1)
table.Rows.Remove(model.row);
else
MessageBox.Show(model.row[0] + "");
}
}
int successCount = records.Where(x => x == 1).Count();
int faultCount = records.Where(x => x == 0).Count();
MessageUtil.Show(ResourceKeys.ImportSuccess + "" + successCount + "条\r\n" + ResourceKeys.ImportFault + "" + faultCount + "条\r\n" + "具体原因请查看错误信息.");
}
}
catch (Exception ex)
{
MessageUtil.Show(ResourceKeys.ImportFault + "\r\n" + ex.Message);
LogHelper.Instance.WriteError(ex);
string Message = ErrorMessage.PromptErrorMessage(ex);
//MessageUtil.Show(Message,ex.Message);
}
}
}
/// <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(',');
//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 = this.gcMain.GridView.ToExcelDataTable(fileName, colFields, true,false,this.SysModel.AutoImportCalMode);
//设置默认值
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);
}
if (this.SearchObj != null)
{
fieldValue = this.SearchObj.ReplaceParentControlValue(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);
}
}
/// <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 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);
}
}
/// <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 (MessageUtil.Show("注意!覆盖功能将替换原有的数据请慎重使用!是否确认覆盖?", MessageBoxButtons.YesNo) != DialogResult.Yes)
return;
List<string> ColumnNameList = GridExtend.ColumnNameList;
string sql = "select * from " + _tableName + " where 1<>1";
//SqlDataAdapter dat = BaseImpl.GetAdapterResult(sql);
DbDataAdapter dat = BaseImpl.GetAdapterResult(sql);
DataTable datatb = new DataTable();
dat.Fill(datatb);
DataTable table = this.gcMain.GridControl.DataSourceTable();
string updateSql = "update {0} set {1} where {2}='{3}';";
int successCount = 0;
string msg = string.Empty;
if (table != null && table.Rows.Count > 0)
{
if (!this.DetermineImportConditions())
{
return;
}
//根据全表字段类型进行默认填充
int currRow = 0;
foreach (DataRow row in table.Rows)
{
string updateFields = string.Empty;
foreach (DataColumn col in table.Columns)
{
if (ColumnNameList.Contains(col.ColumnName) &&datatb.Columns.Contains(col.ColumnName) && table.Columns.Contains(col.ColumnName))
{
GridColumn gridCol = this.gcMain.GridView.Columns[col.ColumnName];
GridColumnModel gridmodel = gridCol.Tag as GridColumnModel;
if (col.ColumnName == _parmaryKey || col.ColumnName == "import_errormsg" || col.ColumnName == "lskjimport_errorFlag") continue;
if ((col.DataType == typeof(DateTime)) && (row[col.ColumnName] + "" == ""))
updateFields += string.Format("[{0}]=null,", col.ColumnName);
else if (gridmodel != null && (gridmodel.FieldType == ControlType.LabTreeType ||
gridmodel.FieldType == ControlType.LabComboxValue ||
gridmodel.FieldType == ControlType.LabComboxValueParam ||
gridmodel.FieldType == ControlType.LabAutoCompleteValue ||
gridmodel.FieldType == ControlType.LabAutoCompleteValueParam ||
gridmodel.FieldType == ControlType.LabMultiSelectValue ||
gridmodel.FieldType == ControlType.LabMultiSelectValueNew ||
gridmodel.FieldType == ControlType.LabMultiSelectValueParam))
{
bool isEmpty = gridmodel.CanNull;
string fieldValue = GetValueByImportText(row, gridCol.FieldName, row[gridCol.FieldName] + "");
if (string.IsNullOrEmpty(fieldValue))
{
if (isEmpty)
{
XtraMessageBox.Show("数据导入错误,未找到对应的编码,请检查!\r\n第" + (currRow + 1).ToString() + "行,第" + (gridCol.VisibleIndex + 1).ToString() + "列-" + gridCol.Caption, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
else
{
GridColumn column = _gridEx.GridView.Columns[gridCol.FieldName];
if (column.ColumnType.Name.ToLower().IndexOf("int") >= 0)
if (column.ColumnType.Name.ToLower() == "string")
updateFields += string.Format("[{0}]='{1}',", gridCol.FieldName, "");
if (column.ColumnType.Name.ToLower().IndexOf("char") >= 0)
updateFields += string.Format("[{0}]='{1}',", gridCol.FieldName, "");
if (column.ColumnType.Name.ToLower().IndexOf("int") >= 0)
updateFields += string.Format("[{0}]='{1}',", gridCol.FieldName, "0");
if (column.ColumnType.Name.ToLower() == "decimal")
updateFields += string.Format("[{0}]='{1}',", gridCol.FieldName, "0");
}
}
else
{
updateFields += string.Format("[{0}]='{1}',", gridCol.FieldName, fieldValue);
}
}
else
{
updateFields += string.Format("[{0}]='{1}',", col.ColumnName, (row[col.ColumnName] + "").Replace("'", "''"));
}
currRow++;
}
}
int ReRows = SqlHelper.ExecuteNonQuery(string.Format(updateSql, _tableName, updateFields.TrimEnd(','), _parmaryKey, row[_parmaryKey]));
successCount += ReRows;
if (ReRows == 0) msg += "\n主键:[" + row[_parmaryKey] + "]更新失败请检查";
}
this._isImported = true;
if (!string.IsNullOrEmpty(_gridEx.LastSearchSql)) _gridEx.SetGridViewDataSource(SqlHelper.ExecuteDataTable(_gridEx.LastSearchSql));
XtraMessageBox.Show("覆盖完成,成功" + successCount + "条" + msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//_gridEx.ParentControl.SearchLastGrid();
}
else
{
MessageUtil.Show(ResourceKeys.NotFountGridData);
}
}
catch (Exception ex)
{
string Message = ErrorMessage.PromptErrorMessage(ex);
MessageUtil.Show(Message, ex.Message);
}
}
/// <summary>
/// <para>说明:导出模版</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 OnExportButtonClick(object sender, EventArgs e)
{
try
{
this.gcMain.GridControl.ToExcelTemplate(_fromText);
}
catch (Exception ex)
{
string Message = ErrorMessage.PromptErrorMessage(ex);
MessageUtil.Show(Message, ex.Message);
}
}
/// <summary>
/// <para>说明:</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="FormClosingEventArgs"/> instance containing the event data.</param>
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);
}
}
/// <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);
}
}
}
}
}