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