using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lskj.Business;
using Lskj.Business.Impl;
using Lskj.Control;
using Lskj.Control.Model;
using Lskj.Core;
using Lskj.Data;
using Lskj.Model;
using Lskj.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Lskj.PubSpecialImport
{
public partial class FrmMain : BaseForm
{
public FrmMain()
{
InitializeComponent();
this.Load += FrmMain_Load;
}
public DynamicPubSpecialImport Model;
public int FirstRowIndex = 0;
///
/// 匹配搜索框列
///
private RepositoryItemGridLookUpEdit searchEdit = new RepositoryItemGridLookUpEdit();
///
/// 缓存列对象
///
private static List ColumnList = new List();
///
/// 导入文件名
///
private string importFileName = "";
///
/// 特殊列值
///
private string specialValue = "";
private static Dictionary ValueGridColumnTable;
private static Dictionary LookupParentKey;
private static List _checkColumns;
private static string _treeColumnName;
#region 事件
///
/// 初始化时
///
///
///
private void FrmMain_Load(object sender, EventArgs e)
{
try
{
bool showType = Model != null && Model.ShowType.Equals("1") && !ERPInfo.Instance.UserName.Equals("管理员");
if (showType)
{
Opacity = 0;
}
InitlizeSpiltLocation();
InitEvents();
InitGridColumns();
InitMulitControl();
InitDataSource();
if (showType)
{
OnBtnReadClick(btnRead, null);
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
}
///
/// 导入按钮点击
///
///
///
private void OnBtnImportClick(object sender, EventArgs e)
{
try
{
bool showType = Model != null && Model.ShowType.Equals("1") && !ERPInfo.Instance.UserName.Equals("管理员");
string fileName = importFileName;
if (File.Exists(fileName))
{
this.Hide();
WaitForm.ShowForm("正在导入数据...");
this.ParentView.GridControl.DataSource = this.ToExcelDataTable(fileName, out int count, out int errorCount, true);
WaitForm.HideForm();
if (!showType)
{
MessageUtil.Show(string.Format("成功导入{0}条数据,错误{1}条数据", count, errorCount));
}
this.Close();
}
else
{
MessageUtil.Show("导入Excel文件不存在");
tipsEdit.Text = "请导入Excel模板";
btnImport.Enabled = false;
}
}
catch (Exception ex)
{
WaitForm.HideForm();
this.Show();
MessageUtil.Show(string.Format("导入失败,原因:{0}", ex.Message));
}
}
///
/// 读取按钮点击
///
///
///
private void OnBtnReadClick(object sender, EventArgs e)
{
bool showType = false;
try
{
showType = Model != null && Model.ShowType.Equals("1") && !ERPInfo.Instance.UserName.Equals("管理员");
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "选择导入文件";
dialog.Filter = SystemInfo.Instance.IsXlsxFirst ? "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls" : "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx";
DialogResult result = dialog.ShowDialog();
DataTable gcData = new DataTable();
if (result == DialogResult.OK)
{
btnImport.Enabled = true;
string fileName = importFileName = dialog.FileName;
tipsEdit.Text = string.Format("当前读取文件:{0},请绑定列后点击导入", Path.GetFileName(fileName));
string colFields = this.gcMain.GridView.Columns.ToString(',');
string[] indexArray = Model.SpecialValueIndex.Split(',');
if (!string.IsNullOrWhiteSpace(Model.SpecialValueIndex) && indexArray.Length == 2)
{
int rowIndex = int.TryParse(indexArray[0], out rowIndex) ? rowIndex : 0;
int colIndex = int.TryParse(indexArray[1], out colIndex) ? colIndex : 0;
specialValue = GetSpecialCellValue(fileName, "", rowIndex, colIndex);
}
//else
//{
// MessageUtil.Show("参数配置错误,导入失败");
// btnImport.Enabled = false;
// tipsEdit.Text = "请导入Excel模板";
// gc_Right.SetGridViewDataSource(new DataTable());
// return;
//}
//if (string.IsNullOrEmpty(specialValue))
//{
// MessageUtil.Show("当前版本为新版bom/旧版bom导入,请检查导入文件是否匹配正确");
// btnImport.Enabled = false;
// tipsEdit.Text = "请导入Excel模板";
// gc_Right.SetGridViewDataSource(new DataTable());
// return;
//}
string[] firstIndexArray = Model.FirstRowIndex.Split(',');
if (firstIndexArray.Length > 0)
{
bool isTitle = false;
foreach (string firstIndex in firstIndexArray)
{
if (int.TryParse(firstIndex, out int index))
{
try
{
DataTable dataTable1 = ExcelToDatatable(fileName, Model.SheetName, index);
FirstRowIndex = index;
isTitle = true;
break;
}
catch (IOException ex)
{
throw new Exception(string.Format("读取模板内容失败,原因:{0}", ex.Message));
}
}
}
if (!isTitle)
{
FirstRowIndex = 0;
}
}
DataTable dataTable = ExcelToDatatable(fileName, Model.SheetName, FirstRowIndex);
DataTable importTable = GetSourceTable(dataTable);
DataTable sourceTable = this.gcMain.GridControl.DataSource as DataTable;
if (dataTable != null)
{
try
{
if (!string.IsNullOrEmpty(Model.ReadTableCond))
{
DataView view = new DataView(dataTable);
view.RowFilter = Model.ReadTableCond;
dataTable = view.ToTable();
}
}
catch (Exception)
{
}
this.gc_Right.SetGridViewDataSource(dataTable);
}
if (sourceTable != null && sourceTable.Rows.Count > 0)
{
if (sourceTable.Rows.Count != importTable.Rows.Count)
{
this.gcMain.SetGridViewDataSource(importTable);
this.condTxtEdit.Text = "";
}
else
{
bool isComplete = true;
int rowCount = importTable.Rows.Count;
if (!string.IsNullOrEmpty(specialValue))
{
rowCount = importTable.Rows.Count - 1;
}
for (int i = 0; i < rowCount; i++)
{
DataRow row = importTable.Rows[i];
int count = sourceTable.Rows.Cast().Where(n => (n["excelFieldName"] + "").Equals(row["excelFieldName"] + "")).Count();
if (count == 0)
{
isComplete = false;
break;
}
}
if (!isComplete)
{
this.gcMain.SetGridViewDataSource(importTable);
this.condTxtEdit.Text = "";
}
else
{
if (!string.IsNullOrEmpty(specialValue) && sourceTable.Rows.Count > 0)
{
sourceTable.Rows[sourceTable.Rows.Count - 1]["excelFieldName"] = specialValue;
}
}
}
}
else
{
this.gcMain.SetGridViewDataSource(importTable);
this.condTxtEdit.Text = "";
}
OnBtnImportClick(btnImport, null);
this.DialogResult = DialogResult.OK;
}
else
{
this.DialogResult = DialogResult.Cancel;
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
btnImport.Enabled = false;
tipsEdit.Text = "请导入Excel模板";
gc_Right.SetGridViewDataSource(new DataTable());
this.DialogResult = DialogResult.Cancel;
}
finally
{
if (showType)
{
FormDialogModel dialogModel = new FormDialogModel()
{
PubDialogType = this.DialogResult == DialogResult.Cancel ? DialogType.Pubcolsed : DialogType.PubAddRecord
};
this.Tag = dialogModel;
Close();
}
}
}
///
/// 确定按钮点击
///
///
///
private void OnBtnOkClick(object sender, EventArgs e)
{
try
{
string condFilter = this.condTxtEdit.Text.Trim();
string condPurview = this.purview_Mulit.EditValue;
string unionColumn = GetUnionColumn();
string sql = "if exists(select * from P_SpecialImportTab where moduleId = '{0}' and rightMenuName = '{1}') " +
"begin " +
"update P_SpecialImportTab set Ls_CondFilter = '{2}',Ls_UnionColumn = '{3}',Ls_CondPurview = '{4}' where moduleId = '{0}' and rightMenuName = '{1}' " +
"end " +
"else begin " +
"insert into P_SpecialImportTab (moduleId,rightMenuName,Ls_CondFilter,Ls_UnionColumn,Ls_CondPurview) values ('{0}','{1}','{2}','{3}','{4}') " +
"end";
sql = string.Format(sql, Model.ModuleCode, Model.MenuName, condFilter.Replace("'", "''"), unionColumn.Replace("'", "''"), condPurview.Replace("'", "''"));
SqlHelper.ExecuteNonQuery(sql);
MessageUtil.Show("保存成功");
}
catch (Exception ex)
{
MessageUtil.Show("保存失败,原因:" + ex.Message);
}
}
///
/// 取消按钮点击
///
///
///
private void OnBtnCancelClick(object sender, EventArgs e)
{
try
{
DataTable dataTable = this.gcMain.GridControl.DataSourceTable();
if (dataTable != null && dataTable.Rows.Count > 0)
{
foreach (DataRow item in dataTable.Rows)
{
item["clientFieldName"] = "";
}
}
}
catch (Exception ex)
{
MessageUtil.Show(string.Format("取消绑定列失败,原因:{0}", ex.Message));
}
}
///
/// 分隔条位置改变时
///
///
///
private void OnSplitMainContainerPositionChanged(object sender, EventArgs e)
{
try
{
if (this.Model != null)
{
IniHelper.Write(string.Format("PubSpecialImport_SplitMain_{0}", this.Model.ModuleCode), this.splitMainContainer.SplitterPosition + "");
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
}
#endregion
#region 方法
///
/// 初始化事件绑定
///
private void InitEvents()
{
this.btnRead.Click += OnBtnReadClick;
this.btnImport.Click += OnBtnImportClick;
this.btnOk.Click += OnBtnOkClick;
this.btnCancel.Click += OnBtnCancelClick;
this.splitMainContainer.SplitterPositionChanged += OnSplitMainContainerPositionChanged;
}
///
/// 设置分割条位置
///
private void InitlizeSpiltLocation()
{
try
{
string splitMainWidth = IniHelper.Read(string.Format("PubSpecialImport_SplitMain_{0}", this.Model.ModuleCode));//通过Key获取Value值
if (!string.IsNullOrEmpty(splitMainWidth))
{
this.splitMainContainer.SplitterPosition = Convert.ToInt32(splitMainWidth);
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
}
///
/// 初始化表格列
///
private void InitGridColumns()
{
this.gcMain.AllowClearColumns = false;
GridColumn excelFieldNameColumn = this.gcMain.GridView.Columns.AddVisible("excelFieldName", "Excel列名");
excelFieldNameColumn.Width = 200;
GridColumn clientFieldNameColumn = this.gcMain.GridView.Columns.AddVisible("clientFieldName", "绑定程序列");
clientFieldNameColumn.Width = 200;
DataTable gridColumnsTab = new DataTable();
if (this.Model.isBase=="1")
{
gridColumnsTab = BaseModuleImpl.GetBaseGridColumns(this.Model.ModuleCode);
}
else
{
gridColumnsTab = BillImpl.GetDetailColumns(this.Model.ModuleCode);
}
searchEdit.View.OptionsView.ShowIndicator = false;
searchEdit.View.OptionsView.ColumnAutoWidth = false;
//searchEdit.PopupSizeable = true;
//searchEdit.PopupResizeMode = ResizeMode.Default;
searchEdit.ImmediatePopup = true;
searchEdit.ShowFooter = false;
searchEdit.NullText = "";
searchEdit.ValueMember = "dm";
searchEdit.DisplayMember = "mc";
searchEdit.View.Columns.AddVisible("dm", "dm").Width = 150;
searchEdit.View.Columns.AddVisible("mc", "mc").Width = 200;
searchEdit.View.OptionsView.ShowColumnHeaders = false;
this.gcMain.GridControl.RepositoryItems.Add(searchEdit);
clientFieldNameColumn.ColumnEdit = searchEdit;
searchEdit.DataSource = GetSearchSourceTable(gridColumnsTab);
searchEdit.View.Tag = searchEdit;
}
///
/// 初始化多选控件
///
private void InitMulitControl()
{
if (!ERPInfo.Instance.UserName.Equals("管理员"))
{
pl_purview.Visible = false;
return;
}
purview_Mulit.LabelText = "";
purview_Mulit.ValueMember = "UserId";
purview_Mulit.TextField = "UserName";
purview_Mulit.ValueField = "UserId";
purview_Mulit.Model = new ControlModel()
{
FieldType = ControlType.LabMultiSelectValue,
};
string fields = string.Empty;
if (BaseImpl.HasExistsColumn("P_EmployeeTab", "SignBmp"))
fields = ",SignBmp";
if (BaseImpl.HasExistsColumn("P_EmployeeTab", "Password"))
fields += ",Password";
if (BaseImpl.HasExistsColumn("P_EmployeeTab", "AD_Id"))
fields += ",AD_Id";
string sqlValue = string.Format("select EmployeeId UserId,LoginAccount UserCode,EmployeeName UserName {0} from P_EmployeeTab WHERE sign=0 and UseFlag=1 order by loginaccount", fields);
DataTable dataSource = SqlHelper.ExecuteDataTable(sqlValue);
purview_Mulit.SourceSQL = sqlValue;
purview_Mulit.SetDataSource(dataSource);
purview_Mulit.TextEdit.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
}
///
/// 初始化数据
///
private void InitDataSource()
{
if (BaseImpl.HasExistsTable("P_SpecialImportTab"))
{
if (!BaseImpl.HasExistsColumn("P_SpecialImportTab", "moduleId"))
{
string addColumnSql = "alter table P_SpecialImportTab add moduleId int";
SqlHelper.ExecuteNonQuery(addColumnSql);
}
if (!BaseImpl.HasExistsColumn("P_SpecialImportTab", "rightMenuName"))
{
string addColumnSql = "alter table P_SpecialImportTab add rightMenuName varchar(100)";
SqlHelper.ExecuteNonQuery(addColumnSql);
}
if (!BaseImpl.HasExistsColumn("P_SpecialImportTab", "Ls_CondFilter"))
{
string addColumnSql = "alter table P_SpecialImportTab add Ls_CondFilter varchar(1000)";
SqlHelper.ExecuteNonQuery(addColumnSql);
}
if (!BaseImpl.HasExistsColumn("P_SpecialImportTab", "Ls_UnionColumn"))
{
string addColumnSql = "alter table P_SpecialImportTab add Ls_UnionColumn varchar(2000)";
SqlHelper.ExecuteNonQuery(addColumnSql);
}
if (!BaseImpl.HasExistsColumn("P_SpecialImportTab", "Ls_CondPurview"))
{
string addColumnSql = "alter table P_SpecialImportTab add Ls_CondPurview varchar(1000)";
SqlHelper.ExecuteNonQuery(addColumnSql);
}
DataTable dataTable = new DataTable();
try
{
string searchSql = string.Format("select * from P_SpecialImportTab where moduleId = '{0}' and rightMenuName = '{1}'", Model.ModuleCode, Model.MenuName);
dataTable = SqlHelper.ExecuteDataTable(searchSql);
}
catch (Exception)
{
}
if (dataTable != null && dataTable.Rows.Count > 0)
{
DataRow dataRow = dataTable.Rows[0];
string condFilter = dataRow["Ls_CondFilter"] + "";
string unionColumn = dataRow["Ls_UnionColumn"] + "";
string condPurview = dataRow["Ls_CondPurview"] + "";
string[] values = condPurview.Trim(',').Split(',');
if (!values.Contains(ERPInfo.Instance.UserId))
{
condTxtEdit.ReadOnly = true;
}
this.condTxtEdit.Text = condFilter;
this.purview_Mulit.EditText = condPurview;
List unionColumnList = unionColumn.Split(',').ToList();
DataTable sourceTable = GetSourceTable(unionColumnList);
this.gcMain.GridControl.DataSource = sourceTable;
}
else
{
if (!ERPInfo.Instance.UserName.Equals("管理员"))
{
MessageUtil.Show("未获取到配置数据\r\n请联系管理员配置数据");
this.Close();
}
}
}
else
{
string createTableSql = "create table P_SpecialImportTab (moduleId int,rightMenuName varchar(100),Ls_CondFilter varchar(1000),Ls_UnionColumn varchar(2000),Ls_CondPurview varchar(1000))";
SqlHelper.ExecuteNonQuery(createTableSql);
}
}
///
/// 判断标题行
///
///
///
///
///
public bool IsTitleRow(string fileName, string sheetName = "", int firstRowIndex = 0)
{
bool isTitle = false;
DataTable data = new DataTable();
FileStream fs;
IWorkbook workbook = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
ISheet sheet;
if (!string.IsNullOrEmpty(sheetName))
{
sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据
}
else
{
//也可以根据sheet编号来获取数据
sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表)
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(firstRowIndex);
}
}
catch (Exception)
{
}
return isTitle;
}
///
/// 获取表格数据
///
///
///
///
///
public DataTable ExcelToDatatable(string fileName, string sheetName = "", int firstRowIndex = 0)
{
DataTable data = new DataTable();
FileStream fs;
IWorkbook workbook = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
ISheet sheet;
if (!string.IsNullOrEmpty(sheetName))
{
sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据
}
else
{
//也可以根据sheet编号来获取数据
sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表)
}
if (sheet != null)
{
int startRow = firstRowIndex + 1;
IRow firstRow = sheet.GetRow(firstRowIndex);
IRow bandRow = null;
int cellCount = firstRow.LastCellNum;
for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)//第一行列数循环
{
ICell titleCell = firstRow.GetCell(i);
ICell bandCell = null;
bool isBandTitle = false;
if (titleCell.IsMergedCell)
{
CellRangeAddress mergrRange = FindMergedRegion(sheet, firstRowIndex, i);
startRow = mergrRange.LastRow + 1;
if (mergrRange != null)
{
if (mergrRange.FirstColumn < mergrRange.LastColumn && !Model.CustomerServiceApp)
{
isBandTitle = true;
bandRow = sheet.GetRow(mergrRange.LastRow + 1);
titleCell = firstRow.GetCell(mergrRange.FirstColumn);
bandCell = bandRow.GetCell(i);
CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i);
if (bandMergrRange != null)
{
startRow = bandMergrRange.LastRow + 1;
}
else
{
startRow = mergrRange.LastRow + 2;
}
}
else
{
startRow = mergrRange.LastRow + 1;
}
}
}
string fieldName = "";
if (!isBandTitle || bandRow == null)
{
fieldName = GetCellValue(titleCell);
}
else
{
fieldName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}";
}
if (string.IsNullOrEmpty(fieldName) && titleCell.IsMergedCell)
{
cellCount -= 1;
continue;
}
DataColumn column = new DataColumn(fieldName);//获取标题
data.Columns.Add(column);//添加列
}
//最后一行的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; i++)//循环遍历所有行
{
IRow row = sheet.GetRow(i);//第几行
if (row == null)
{
continue; //没有数据的行默认是null;
}
//将excel表每一行的数据添加到datatable的行中
DataRow dataRow = data.NewRow();
for (int j = firstRow.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
if (SystemInfo.Instance.ImportRemoveSpaces && (row.GetCell(j).CellType == CellType.String))
{
// 清除字符串前后空格
string cellValue = GetCellValue(row.GetCell(j)).Trim();
dataRow[j - firstRow.FirstCellNum] = cellValue;
}
else
{
dataRow[j - firstRow.FirstCellNum] = GetCellValue(row.GetCell(j));
}
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (IOException ex)
{
throw new IOException(string.Format("读取模板内容失败,原因:{0}", ex.Message));
}
catch (Exception ex)
{
throw new Exception(string.Format("读取模板内容失败,原因:{0}", ex.Message));
}
}
///
/// 获取特殊单元格的值
///
///
public string GetSpecialCellValue(string fileName, string sheetName = "", int rowIndex = 0, int colIndex = 0)
{
string value = "";
FileStream fs;
IWorkbook workbook = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > 0) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
ISheet sheet;
if (!string.IsNullOrEmpty(sheetName))
{
sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据
}
else
{
//也可以根据sheet编号来获取数据
sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表)
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(rowIndex);
value = GetCellValue(firstRow.GetCell(colIndex));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return value;
}
///
/// 获取数据源
///
///
private DataTable GetSourceTable(DataTable dataTable)
{
DataTable sourceTable = new DataTable();
sourceTable.Columns.Add("excelFieldName");
sourceTable.Columns.Add("clientFieldName");
if (dataTable != null)
{
foreach (DataColumn col in dataTable.Columns)
{
DataRow dataRow = sourceTable.NewRow();
dataRow["excelFieldName"] = col.ColumnName;
sourceTable.Rows.Add(dataRow);
}
}
if (!string.IsNullOrEmpty(specialValue))
{
DataRow dataRow = sourceTable.NewRow();
dataRow["excelFieldName"] = specialValue;
sourceTable.Rows.Add(dataRow);
}
return sourceTable;
}
///
/// 获取数据源
///
///
private DataTable GetSourceTable(List unionColumnList)
{
DataTable sourceTable = new DataTable();
sourceTable.Columns.Add("excelFieldName");
sourceTable.Columns.Add("clientFieldName");
if (unionColumnList != null)
{
foreach (string unionColumn in unionColumnList)
{
string[] unionCilumnArray = unionColumn.Split('^');
if (unionCilumnArray.Length == 2)
{
DataRow dataRow = sourceTable.NewRow();
dataRow["excelFieldName"] = unionCilumnArray[0];
dataRow["clientFieldName"] = unionCilumnArray[1];
sourceTable.Rows.Add(dataRow);
}
}
}
return sourceTable;
}
///
/// 获取搜索数据源
///
///
private DataTable GetSearchSourceTable(DataTable dataTable)
{
DataTable sourceTable = new DataTable();
sourceTable.Columns.Add("dm");
sourceTable.Columns.Add("mc");
if (dataTable != null && dataTable.Rows.Count > 0)
{
foreach (DataRow row in dataTable.Rows)
{
GridColumnModel model = new GridColumnModel(row);
if (model.Visible)
{
DataRow dataRow = sourceTable.NewRow();
dataRow["dm"] = row["fieldname"];
string username = row["username"] + "";
if (string.IsNullOrEmpty(username))
{
username = row["fieldname"] + "";
}
dataRow["mc"] = username;
sourceTable.Rows.Add(dataRow);
}
}
}
return sourceTable;
}
///
/// 获取关联列数据
///
///
private string GetUnionColumn()
{
string unionColumn = "";
DataTable sourceTable = this.gcMain.GridControl.DataSourceTable();
if (sourceTable != null)
{
foreach (DataRow row in sourceTable.Rows)
{
unionColumn += string.Format("{0}^{1},", row["excelFieldName"], row["clientFieldName"]);
}
}
return unionColumn.TrimEnd(',');
}
///
/// 导入到表格中
///
///
///
///
///
///
private DataTable ToExcelDataTable(string fileName, out int count, out int errorCount, bool isDirectImport = false, bool isBillImport = false)
{
count = 0;
errorCount = 0;
GridView gridView = ParentView;
DataTable columnsTable = gcMain.gridControl.DataSourceTable();
DataTable table = gridView.GridControl.DataSourceTable();
DataTable sourceDataTable = ExcelToDatatable(fileName, Model.SheetName, FirstRowIndex);
DataView filterDataView = new DataView(sourceDataTable);
try
{
if (!string.IsNullOrEmpty(Model.ReadTableCond))
{
filterDataView.RowFilter = Model.ReadTableCond;
}
}
catch (Exception)
{
}
List dataRows = columnsTable.Rows.Cast().Where(n => !string.IsNullOrEmpty(n["excelFieldName"] + "") && !string.IsNullOrEmpty(n["clientFieldName"] + "")).ToList();
int index = gridView is BandedGridView ? FirstRowIndex + 1 : FirstRowIndex;
isBillImport = index == FirstRowIndex ? 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 firstRow = sheet.GetRow(index);
IRow bandRow = null;
int startRow = FirstRowIndex + 1;
string bandTitel = string.Empty;
ColumnList.Clear();
int cellCount = firstRow.LastCellNum;
// 添加列
for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)
{
ICell titleCell = firstRow.GetCell(i);
ICell bandCell = null;
bool isBandTitle = false;
if (titleCell.IsMergedCell)
{
CellRangeAddress mergrRange = FindMergedRegion(sheet, index, i);
startRow = mergrRange.LastRow + 1;
if (mergrRange != null)
{
if (mergrRange.FirstColumn < mergrRange.LastColumn && !Model.CustomerServiceApp)
{
isBandTitle = true;
bandRow = sheet.GetRow(mergrRange.LastRow + 1);
titleCell = firstRow.GetCell(mergrRange.FirstColumn);
bandCell = bandRow.GetCell(i);
CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i);
if (bandMergrRange != null)
{
startRow = bandMergrRange.LastRow + 1;
}
else
{
startRow = mergrRange.LastRow + 2;
}
}
else
{
startRow = mergrRange.LastRow + 1;
}
}
}
string headerName = "";
if (!isBandTitle || bandRow == null)
{
headerName = GetCellValue(titleCell);
}
else if (!string.IsNullOrEmpty(GetCellValue(bandCell)))
{
headerName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}";
}
if (string.IsNullOrEmpty(headerName))
{
cellCount -= 1;
continue;
}
DataRow row = columnsTable.Rows.Cast().Where(x => (x["excelFieldName"] + "").Equals(headerName)).FirstOrDefault();
headerName = row != null ? row["clientFieldName"] + "" : headerName;
if (string.IsNullOrWhiteSpace(headerName))
{
continue;
}
GridColumn col = gridView.Columns.OfType().FirstOrDefault(x => x.FieldName.Equals(headerName));
if (col != null)
{
if (!table.Columns.Contains(col.FieldName))
{
table.Columns.Add(col.FieldName, col.ColumnType);
}
ColumnList.Add(col.Tag as GridColumnModel);
}
else
{
MessageUtil.Show("未找到列->" + headerName + "");
}
}
InitializeValueGrid();
bool AutoImportCal = SystemInfo.Instance.AutoImportCal;//是否执行计算公式
for (int i = startRow; i <= sheet.LastRowNum; i++)
{
ToAssignment = true;
CurrentRow = i;
DataRow rowSource = sourceDataTable.Rows[i - startRow];
if (!filterDataView.Cast().Any(rowView => rowView.Row == rowSource) || !ValidateCond(condTxtEdit.Text, rowSource))
{
continue;
}
GridColumn col = new GridColumn();
IRow row = sheet.GetRow(i);
if (row == null) continue;
bandTitel = string.Empty;
DataRow specialDataRow = dataRows.Where(n => (n["excelFieldName"] + "").Equals(specialValue)).FirstOrDefault();
string specialFieldName = specialDataRow != null ? specialDataRow["clientFieldName"] + "" : "";
DataRow dataRow = table.NewRow();
//if (i == sheet.LastRowNum && fileExt == ".xlsx") break;
for (int j = row.FirstCellNum; j < firstRow.LastCellNum; j++)
{
CurrentColumn = j;
ICell cell = row.GetCell(j);
ICell titleCell = firstRow.GetCell(j);
ICell bandCell = null;
bool isBandTitle = false;
if (titleCell.IsMergedCell)
{
CellRangeAddress mergrRange = FindMergedRegion(sheet, index, j);
startRow = mergrRange.LastRow + 1;
if (mergrRange != null)
{
if (mergrRange.FirstColumn < mergrRange.LastColumn && !Model.CustomerServiceApp)
{
isBandTitle = true;
bandRow = sheet.GetRow(mergrRange.LastRow + 1);
titleCell = firstRow.GetCell(mergrRange.FirstColumn);
bandCell = bandRow.GetCell(j);
CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, j);
if (bandMergrRange != null)
{
startRow = bandMergrRange.LastRow + 1;
}
else
{
startRow = mergrRange.LastRow + 2;
}
}
else
{
startRow = mergrRange.LastRow + 1;
}
}
}
if (!isBandTitle || bandRow == null)
{
columnName = GetCellValue(titleCell);
}
else if (!string.IsNullOrEmpty(GetCellValue(bandCell)))
{
columnName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}";
}
if (string.IsNullOrEmpty(columnName))
{
continue;
}
DataRow colDataRow = dataRows.Where(n => (n["excelFieldName"] + "").Equals(columnName)).FirstOrDefault();
if (colDataRow == null)
{
continue;
}
columnName = colDataRow["clientFieldName"] + "";
//if (!bandTitel.Equals(Bandcell + "") && !string.IsNullOrEmpty(Bandcell + "")) bandTitel = Bandcell + "";
col = gridView.Columns.OfType().FirstOrDefault(x => x.FieldName.Equals(columnName));
if (col == null) continue;
GridColumnModel model = col.Tag as GridColumnModel;
if (cell != null)
{
try
{
if (cell.CellType == CellType.Blank)
{
continue;
}
if (SystemInfo.Instance.ImportRemoveSpaces && cell.CellType == CellType.String)
{
// 清除字符串前后空格
string cellValue = cell.StringCellValue.Trim();
cell.SetCellValue(cellValue);
}
if (cell.CellType == CellType.Numeric && (cell + "").StartsWith("-"))
{
dataRow[col.FieldName] = cell.NumericCellValue;
if (AutoImportCal)
{
if (!string.IsNullOrEmpty(model.UnionFields))
{
SetUnionValue(model, dataRow[col.FieldName] + "", dataRow);
}
SetCalcValue(model, dataRow[col.FieldName] + "", dataRow);
}
}
else
{
if (cell.CellType == CellType.Numeric)
{
//GridColumnModel model = col.Tag as GridColumnModel;
if (model != null && isDirectImport && (model.FieldType == ControlType.LabDate ||
model.FieldType == ControlType.LabDateTime ||
model.FieldType == ControlType.LabDateTimeShort ||
model.FieldType == ControlType.LabTime ||
model.FieldType == ControlType.LabShortTime))
{
string fieldValue = ToDateTimeValue(cell.NumericCellValue + "");
if (fieldValue != "")
{
dataRow[col.FieldName] = Convert.ToDateTime(fieldValue);
if (AutoImportCal)
{
if (!string.IsNullOrEmpty(model.UnionFields))
{
SetUnionValue(model, dataRow[col.FieldName] + "", dataRow);
}
SetCalcValue(model, dataRow[col.FieldName] + "", dataRow);
}
}
}
else
{
dataRow[col.FieldName] = cell.NumericCellValue;
if (AutoImportCal)
{
if (!string.IsNullOrEmpty(model.UnionFields))
{
SetUnionValue(model, dataRow[col.FieldName] + "", dataRow);
}
SetCalcValue(model, dataRow[col.FieldName] + "", dataRow);
}
}
}
else
{
//GridColumnModel model = col.Tag as GridColumnModel;
if (model != null && isDirectImport && (model.FieldType == ControlType.LabTreeType ||
model.FieldType == ControlType.LabComboxValue ||
model.FieldType == ControlType.LabComboxValueParam ||
model.FieldType == ControlType.LabAutoCompleteValue ||
model.FieldType == ControlType.LabAutoCompleteValueParam ||
model.FieldType == ControlType.LabMultiSelectValue ||
model.FieldType == ControlType.LabMultiSelectValueNew ||
model.FieldType == ControlType.LabMultiSelectValueParam
|| model.FieldType == ControlType.LabTreeLookValue
))
{
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) && GetCellValue(cell).Contains(","))
{
string[] cellText = GetCellValue(cell).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
{
dataRow[col.FieldName] = fieldValue;
if (AutoImportCal)
{
if (!string.IsNullOrEmpty(model.UnionFields))
{
SetUnionValue(model, dataRow[col.FieldName] + "", dataRow);
}
SetCalcValue(model, dataRow[col.FieldName] + "", dataRow);
}
}
}
else
{
IRichTextString richTextString = (IRichTextString)cell.RichStringCellValue;
if (fileExt == ".xlsx")
{
cell.SetCellValue(richTextString);
}
else if (fileExt == ".xls")
{
string cellValue = string.Empty;
for (int m = 0; m < richTextString.Length; m++)
{
//string aaa = richTextString.String.Substring(m , 1);
//short aaa = richTextString.GetFontAtIndex(m);
IFont font = sheet.Workbook.GetFontAt(richTextString.GetFontAtIndex(m));//richTextString.GetFontAtIndex(m)
string str = string.Empty;
string code = richTextString.ToString().Substring(m, 1);
switch (font.TypeOffset)
{
case FontSuperScript.Sub:
str = ChemistryHelper.GetSubChar(code);
break;
case FontSuperScript.Super:
str = ChemistryHelper.GetSuperChar(code);
break;
default:
str = code;
break;
}
cellValue = cellValue + str;
}
cell.SetCellValue(cellValue);
}
dataRow[col.FieldName] = GetCellValue(cell);
if (AutoImportCal)
{
if (!string.IsNullOrEmpty(model.UnionFields))
{
SetUnionValue(model, dataRow[col.FieldName] + "", dataRow);
}
SetCalcValue(model, dataRow[col.FieldName] + "", dataRow);
}
}
}
}
}
catch (Exception)
{
throw;
}
}
}
if (!string.IsNullOrEmpty(specialFieldName) && dataRow.Table.Columns.Contains(specialFieldName))
{
dataRow[specialFieldName] = specialValue;
}
table.Rows.Add(dataRow);
count += 1;
}
ToAssignment = false;
}
catch (InvalidOperationException ex)
{
if (ToAssignment && (CurrentRow != 0 || CurrentColumn != 0))
{
string value = string.Format("第{0}行,第{1}列 {2},值出现异常", CurrentRow, CurrentColumn + 1, columnName);
MessageUtil.Show(value);
}
else
{
MessageUtil.Show(ResourceKeys.DeleteLastTotalRow);
}
}
catch (IOException exe)
{
//string Message = ErrorMessage.PromptErrorMessage(exe);
//MessageUtil.Show(Message, exe.Message);
MessageUtil.Show(string.Format(ResourceKeys.UseingFile, Path.GetFileName(fileName)));
}
catch (Exception ex)
{
//MessageUtil.Show(ResourceKeys.ImportFault + ex.Message);
LogUtil.WriteError("读取excel出错!", ex);
string Message = ErrorMessage.PromptErrorMessage(ex);
MessageUtil.Show(Message, ex.Message);
}
return table.TrimEmptyRows();
}
///
/// 导入表的时候将下拉框的值存储
///
///
private void InitializeValueGrid()
{
GridView gridView = ParentView;
ValueGridColumnTable = new Dictionary();
_checkColumns = new List();
LookupParentKey = new Dictionary();
foreach (GridColumn col in gridView.Columns)
{
if (col.Tag is GridColumnModel)
{
GridColumnModel model = col.Tag as GridColumnModel;
if (model != null && !ValueGridColumnTable.ContainsKey(model))
{
if (model.FieldType == ControlType.LabTreeType ||
model.FieldType == ControlType.LabComboxValue ||
model.FieldType == ControlType.LabComboxValueParam ||
model.FieldType == ControlType.LabAutoCompleteValue ||
model.FieldType == ControlType.LabAutoCompleteValueParam ||
model.FieldType == ControlType.LabMultiSelectValue ||
model.FieldType == ControlType.LabMultiSelectValueNew ||
model.FieldType == ControlType.LabMultiSelectValueParam
|| model.FieldType == ControlType.LabTreeLookValue
)
{
string sqlValue = model.SqlSource;
if (sqlValue.Contains(" #"))
{
//sqlValue = sqlValue.Replace("#", "");
Match m = Regex.Match(sqlValue, @"#([\s\S]*?)#");
//处理带参数上一级编码过滤问题,需在带参数sql中增加名称的父级字段
if (m.Success)
{
sqlValue = ReplaceHelper.ReplaceParam(sqlValue);
LookupParentKey.Add(model.FieldName, m.Value.Replace("#", ""));
}
}
ValueGridColumnTable.Add(model, BaseImpl.GetDataTableResult(sqlValue));
if (model.FieldType == ControlType.LabTreeType)
{
_treeColumnName = model.FieldName;
}
}
if (model.FieldType == ControlType.LabCheckBox)
{
_checkColumns.Add(col.FieldName.ToLower());
}
}
}
}
}
///
/// 计算列关联字段
///
///
///
///
private void SetUnionValue(GridColumnModel model, string fieldValue, DataRow rowItem)
{
//DataTable table = gcMain.gridControl.DataSourceTable();
//DataRow rowItem = this.gridView.GetFocusedDataRow();
string unionValues = model.UnionValues;
if (rowItem != null && model != null)
{
// if (this.ControlObj != null)
// unionValues = this.ControlObj.ReplaceParentControlValue(unionValues);
unionValues = ReplaceHelper.ReplaceRowParam(rowItem, unionValues.Replace("{" + model.FieldName + "}", fieldValue));
try
{
string[] fields = model.UnionFields.Trim(',').Split(',');
DataRow rowResult = BaseImpl.GetDataRowResult(unionValues);
if (rowResult != null)
{
for (int i = 0; i < fields.Length; i++)
{
string field = fields[i];
string value = rowResult.Table.Columns.Contains(field) ? rowResult[field] + "" : null;
rowItem[field] = value;
}
}
else
{
// 设置为空
for (int i = 0; i < fields.Length; i++)
{
string field = fields[i];
rowItem[field] = DBNull.Value;
}
}
}
catch (Exception ex)
{
LogHelper.Instance.WriteError(ex);
LogUtil.WriteError("计算列关联字段--错误-->" + unionValues, ex);
}
}
}
///
/// 计算列计算公式
///
///
///
///
private void SetCalcValue(GridColumnModel model, string fieldValue, DataRow rowItem)
{
try
{
if (rowItem != null && model != null)
{
foreach (GridColumn col in this.ParentView.Columns)
{
GridColumnModel colModel = col.Tag as GridColumnModel;
if (colModel == null) continue;
string defultValue = colModel.DefaultValue;
if (colModel.FieldType == 7 && rowItem.Table.Columns.Contains(col.FieldName) && string.IsNullOrEmpty(rowItem[col.FieldName] + "") && !string.IsNullOrEmpty(colModel.DefaultValue))
{
defultValue = ReplaceHelper.ReplaceUserInfo(colModel.DefaultValue);
if (defultValue.StartsWith("@"))
{
defultValue = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, defultValue));
}
if (IsNumberic(defultValue)) rowItem[col.FieldName] = defultValue;//colModel.DefaultValue;
}
}
List calcModels = ColumnList.FindAll(x => !string.IsNullOrEmpty(x.CalcExpr)).OrderBy(y => y.CalcOrder).ToList();
foreach (GridColumnModel gridModel in calcModels)
{
// 计算顺序小于当前控件则不计算
if (gridModel.CalcOrder < model.CalcOrder) continue;
if (!gridModel.FieldName.Equals(model.FieldName, StringComparison.OrdinalIgnoreCase))
{
bool isTruncate = false;
string calcExpr = gridModel.CalcExpr;
if (calcExpr.StartsWith("@truncate:"))
{
calcExpr = calcExpr.Substring(10);
isTruncate = true;
}
try
{
string result = string.Empty;
if (calcExpr.StartsWith("@"))
{
result = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, calcExpr));
}
else
{
calcExpr = ReplaceHelper.ReplaceRowParam(rowItem, calcExpr);
result = EvalHelper.Eval2(ReplaceHelper.ReplaceEvalCond(calcExpr)) + "";
}
if (isTruncate)
{
result += result.Contains(".") ? "0000000000" : ".0000000000";
rowItem[gridModel.FieldName] = result.Substring(0, result.IndexOf(".")) + result.Substring(result.IndexOf("."), model.Decimals + 1);
//this.gridView.SetRowCellValue(this.gridView.FocusedRowHandle, this.gridView.Columns[gridModel.FieldName], result.Substring(0, result.IndexOf(".")) + result.Substring(result.IndexOf("."), model.Decimals + 1));
}
else
{
try
{
double d = 0;
if (!string.IsNullOrEmpty(result) &&
!"NaN".Equals(result, StringComparison.OrdinalIgnoreCase) &&
!"非数字".Equals(result, StringComparison.OrdinalIgnoreCase) &&
!"undefined".Equals(result, StringComparison.OrdinalIgnoreCase) &&
result != "∞" && result != "-∞" &&
!"正无穷大".Equals(result, StringComparison.OrdinalIgnoreCase) &&
!"负无穷大".Equals(result, StringComparison.OrdinalIgnoreCase) &&
double.TryParse(result, out d))
{
if (string.IsNullOrEmpty(gridModel.DataFormat))
{
result = Math.Round(Convert.ToDouble(d), model.Decimals, MidpointRounding.AwayFromZero) + "";
}
else
{
//计算后先执行保存小数位数
if (SystemInfo.Instance.ComputeFormatting) result = string.Format("{0:" + gridModel.DataFormat + "}", Convert.ToDecimal(result));
}
if (model.FieldType == 7 && result.Contains('%'))
{
result = (double.Parse(result.Replace("%", "")) * 0.01).ToString();
}
rowItem[gridModel.FieldName] = result;
// 判断计算列有无关联值
GridColumnModel UnionModel = calcModels.FirstOrDefault(x => x.FieldName == gridModel.FieldName);
if (!string.IsNullOrEmpty(UnionModel.UnionFields))
{
this.SetUnionValue(UnionModel, rowItem[gridModel.FieldName] + "", rowItem);
}
//this.gridView.SetRowCellValue(this.gridView.FocusedRowHandle, this.gridView.Columns[gridModel.FieldName], result);
}
}
catch (Exception)
{
}
}
}
catch (Exception ex)
{
LogHelper.Instance.WriteError(ex);
LogUtil.WriteError("计算列计算公式--错误-->" + rowItem[gridModel.FieldName], ex);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
///
/// 判断输入的字符串是否可以转换成数值类型
///
///
///
public static bool IsNumberic(string str)
{
double vsNum;
bool isNum;
isNum = double.TryParse(str, System.Globalization.NumberStyles.Float,
System.Globalization.NumberFormatInfo.InvariantInfo, out vsNum);
return isNum;
}
///
/// 获取导入到下拉框里的显示值
///
///
///
///
///
///
public static string GetValueByImportText(DataRow row, string fieldName, string text, bool isBillImport = false)
{
string value = text;
foreach (GridColumnModel model in ValueGridColumnTable.Keys)
{
if (model.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase))
{
string selWhere = "1=1";
DataTable table = ValueGridColumnTable[model];
if (table != null && table.Rows.Count > 0)
{
DataRow rowItemValue = table.Rows.Cast().FirstOrDefault(x => x[model.TextMember] + "" == text);
DataRow rowItemText = table.Rows.Cast().FirstOrDefault(x => x[model.ValueMember] + "" == text);
value = rowItemValue != null ? rowItemValue[isBillImport ? model.ValueMember : model.TextMember] + "" : rowItemText != null ? rowItemText[isBillImport ? model.ValueMember : model.TextMember] + "" : "";
}
else
value = "";
}
}
return value;
}
///
/// 数字转换时间格式
///
///
/// 日期/时间格式
private static string ToDateTimeValue(string strNumber)
{
string returnData = "";
if (!string.IsNullOrWhiteSpace(strNumber))
{
if (!string.IsNullOrWhiteSpace(strNumber))
{
DateTime dateTime = DateTime.FromOADate(Convert.ToDouble(strNumber));
returnData = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
}
}
return returnData;
}
///
/// 说明:检查可用条件
/// 创建日期:2024-3-19
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// The cond.
/// The data row.
/// true if XXXX, false otherwise.
public bool ValidateCond(string cond, DataRow dataRow)
{
bool result = false;
try
{
cond = ReplaceHelper.ReplaceRowParam(dataRow, cond);
if (cond.StartsWith("@") || cond.StartsWith("!"))
{
result = "1".Equals(BaseImpl.GetDefaultValue(cond));
}
else if (dataRow == null)
{
result = ReplaceHelper.EvalCond(cond);
}
else
{
result = ReplaceHelper.ReplaceRowParamCond(dataRow, cond);
}
}
catch (Exception)
{
}
return result;
}
///
/// 获取合并区域
///
///
///
///
///
private CellRangeAddress FindMergedRegion(ISheet sheet, int rowIndex, int columnIndex)
{
int mergedRegionsCount = sheet.NumMergedRegions;
for (int i = 0; i < mergedRegionsCount; i++)
{
CellRangeAddress mergedRegion = sheet.GetMergedRegion(i);
if (mergedRegion.IsInRange(rowIndex, columnIndex))
{
return mergedRegion; // 返回合并区域
}
}
return null; // 未找到合并区域
}
///
/// 获取单元格值
///
///
///
public static string GetCellValue(ICell cell)
{
string cellValue = "";
try
{
if (cell != null)
{
// 根据单元格类型获取值
switch (cell.CellType)
{
case CellType.String:
cellValue = cell.StringCellValue;
break;
case CellType.Numeric:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.Boolean:
cellValue = cell.BooleanCellValue.ToString();
break;
case CellType.Formula://单元格中带有公式,根据类型继续判断
switch (cell.CachedFormulaResultType)
{
case CellType.String:
cellValue = cell.StringCellValue;