// 开始具体的调试操作 private static void DoSomething(Application app) { Worksheet sht = app.ActiveSheet; Workbook wkbk = app.ActiveWorkbook; var rg = app.InputBox("选择要进行小计行删除的第一页数据,包括小计行。", Type: 8) as Range; if (rg != null) { var sumRows = ExcelFunction.GetMultipleRowNum(app, "选择第一页中的多个小计行:"); if (sumRows.Count == 0) { return; } // int?lastRow = ExcelFunction.GetRowNum(app, "选择要处理的最后一行数据的行号:"); if (lastRow == null) { return; } // SumRowHandler.DeleteSumupRow(app, page1: rg, sumRows: sumRows, lastRow: lastRow.Value); } }
public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context) { if (this.ArgumentsAreValid(arguments, 2, out eErrorType argumentError) == false) { return(new CompileResult(argumentError)); } var funcNum = ArgToInt(arguments, 0); if (context.Scopes.Current.Parent != null && context.Scopes.Current.Parent.IsSubtotal) { return(CreateResult(0d, DataType.Decimal)); } ExcelFunction function = null; if (!_functions.ContainsKey(funcNum)) { return(new CompileResult(eErrorType.Value)); } else { function = _functions[funcNum]; } var actualArgs = arguments.Skip(1); if (actualArgs.All(a => a.Value == null)) { return(new CompileResult(0, DataType.Integer)); } var compileResult = function.Execute(actualArgs, context); compileResult.IsResultOfSubtotal = true; return(compileResult); }
public ExcelFunction LoadAndGetExcelFunction(string functionName) { var delegates = new List <Delegate>(); var functionAttributes = new List <object>(); var functionArgumentAttributes = new List <List <object> >(); var assembly = Assembly.GetAssembly(typeof(XLEquities)); StaticData.Load(); ExcelTypeConverter.AddConvertersFrom(Assembly.GetAssembly(typeof(AddIn))); FunctionRegistration.GetDelegatesAndAttributes(assembly, "QSA", new Dictionary <string, bool>(), ref delegates, ref functionAttributes, ref functionArgumentAttributes); ExcelFunction func = null; foreach (var d in delegates) { func = (ExcelFunction)d.Target; if (func.GetName() == functionName) { return(func); } } throw new InvalidOperationException($"{functionName} is not an available Excel function."); }
/// <summary> /// 删除小计行,并将同一Sheet中的多个工程量表进行合并 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_MergeSumRow_Click(object sender, RibbonControlEventArgs e) { Application app = Globals.ThisAddIn.Application; var sht = app.ActiveSheet as Worksheet; // var rg = app.InputBox("选择要进行小计行删除的第一页数据,包括小计行。", Type: 8) as Range; if (rg != null) { var sumRows = ExcelFunction.GetMultipleRowNum(app, "选择第一页中的多个小计行:"); if (sumRows.Count == 0) { return; } // int?lastRow = ExcelFunction.GetRowNum(app, "选择要处理的最后一行数据:"); if (lastRow == null) { return; } // SumRowHandler.DeleteSumupRow(app, page1: rg, sumRows: sumRows, lastRow: lastRow.Value); } app.ScreenUpdating = true; }
/// <summary> /// 对于有很多行数据的工程量表,自动将多数据行进行分隔,并插入小计行 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_SumupInsertRow_Click(object sender, RibbonControlEventArgs e) { Application app = Globals.ThisAddIn.Application; var sht = app.ActiveSheet as Worksheet; // var rg = app.InputBox("选择第二页表格中的区域(包括第一页表格中的小计行,以及第二页表格中最后一行)", Type: 8) as Range; if (rg != null) { int?lastRow = ExcelFunction.GetRowNum(app, "最后一行数据:"); if (lastRow != null) { var sumupRow = rg.Rows[1] as Range; Range indexColumn = sht.Range[rg.Cells[2, 1], rg.Cells[rg.Rows.Count - 1, 1]] as Range; var startRow = sumupRow.Row + 1; var dataRowsCount = indexColumn.Count; // SumRowHandler.InsertSumupRow(app, sumupRow: sumupRow, indexColumn: indexColumn, startRow: startRow, dataRowsCount: dataRowsCount, lastRow: lastRow.Value); } else { MessageBox.Show(@"请输入一个数值"); } } app.ScreenUpdating = true; }
/// <summary> /// 构造函数 /// </summary> /// <param name="DataSheet">图表对应的数据工作表</param> /// <param name="DrawingChart">Excel图形所在的Chart对象</param> /// <param name="ParentApp">此图表所在的Excel类的实例对象</param> /// <param name="type">此图表所属的类型,由枚举drawingtype提供</param> /// <param name="CanRoll">是图表是否可以滚动,即是动态图还是静态图</param> /// <param name="Info">图表中用来显示相关信息的那个文本框对象</param> /// <param name="DrawingTag">每一个监测曲线图的相关信息</param> /// <param name="MonitorType">监测数据的类型,比如测斜数据、立柱垂直位移数据、支撑轴力数据等</param> /// <remarks></remarks> public ClsDrawing_Mnt_Base(Excel.Worksheet DataSheet, Microsoft.Office.Interop.Excel.Chart DrawingChart, Cls_ExcelForMonitorDrawing ParentApp, DrawingType type, bool CanRoll, Excel.TextFrame2 Info, MonitorInfo DrawingTag, MntType MonitorType) { try { //设置Excel窗口与Chart的尺寸 this.F_Application = ParentApp.Application; ExcelFunction.SetLocation_Size(this.ChartSize_sugested, DrawingChart, this.Application, true); // this.Sheet_Data = DataSheet; this.F_myChart = DrawingChart; this.F_textbox_Info = Info; this.Sheet_Drawing = DrawingChart.Parent.Parent; this.F_blnCanRoll = CanRoll; this.F_DrawingType = type; this.P_MntType = MonitorType; //将此对象添加进其所属的集合中 F_Class_ParentApp = ParentApp; // this.P_Key = System.Convert.ToInt32(F_Class_ParentApp.Mnt_Drawings.Add(this)); this.F_UniqueID = GeneralMethods.GetUniqueID(); // this.Tags = DrawingTag; } catch (Exception ex) { MessageBox.Show("创建基本监测曲线图出错。" + "\r\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="DataSheet">图表对应的数据工作表</param> /// <param name="DrawingChart">Excel图形所在的Chart对象</param> /// <param name="ParentApp">此图表所在的Excel类的实例对象</param> /// <param name="DateSpan">此图表的TimeSpan跨度</param> /// <param name="type">此图表的类型,则枚举DrawingType提供</param> /// <param name="CanRoll">是图表是否可以滚动,即是动态图还是静态图</param> /// <param name="date_ColNum">此测斜点的监测数据工作表中的每一天与其在工作表中对应的列号, /// 以监测数据的日期key索引数据所在列号item</param> /// <param name="usedRg">监测曲线的数据范围,此Range对象中, /// 包括此工作表的UsedRange中的第一列,即深度的数据;但是不包括第一行的日期数据</param> /// <param name="Info">记录数据信息的文本框</param> /// <param name="FirstSeriesTag">第一条数据系列对应的Tag信息</param> /// <param name="ProcessRegionData">在施工进度工作表中,每一个基坑区域相关的各种信息,比如区域名称,区域的描述, /// 区域数据的Range对象,区域所属的基坑ID及其ID的数据等</param> /// <remarks></remarks> public ClsDrawing_Mnt_Incline(Excel.Worksheet DataSheet, Excel.Chart DrawingChart, Cls_ExcelForMonitorDrawing ParentApp, DateSpan DateSpan, DrawingType type, bool CanRoll, TextFrame2 Info, MonitorInfo DrawingTag, MntType MonitorType, Dictionary <DateTime, int> date_ColNum, Excel.Range usedRg, SeriesTag_Incline FirstSeriesTag, clsData_ProcessRegionData ProcessRegionData = null) : base(DataSheet, DrawingChart, ParentApp, type, CanRoll, Info, DrawingTag, MonitorType, DateSpan, new clsDrawing_Mnt_RollingBase.SeriesTag(FirstSeriesTag.series, FirstSeriesTag.ConstructionDate)) { // // -------------------------------------------- try { ClsDrawing_Mnt_Incline with_1 = this; with_1.P_rgMntData = usedRg; //'包括第一列,但是不包括第一行的日期。 Excel.Range colRange = usedRg.Columns[1] as Excel.Range; with_1.F_YValues = ExcelFunction.ConvertRangeDataToVector <Single>(colRange); with_1.Information = Info; with_1._ExcavationDepth_lineAndTextbox = FirstSeriesTag; with_1.F_dicDateAndColumnNumber = date_ColNum; with_1.P_ProcessRegionData = ProcessRegionData; with_1._inclineTopElevaion = Project_Expo.InclineTopElevaion; // ----- 集合数据的记录 with_1.F_DicSeries_Tag[(int)LowIndexOfObjectsInExcel.SeriesInSeriesCollection] = FirstSeriesTag; // -----对图例进行更新--------- //Call LegendRefresh(List_HasCurve) } catch (Exception ex) { MessageBox.Show("构造测斜曲线图出错。" + "\r\n" + ex.Message + "\r\n" + ex.TargetSite.Name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void readExcel(string url) { if (string.IsNullOrEmpty(url)) { return; } if (excelDict == null) { excelDict = new Dictionary <string, ExcelStateObj>(); } excelDict.Clear(); excelName = System.IO.Path.GetFileNameWithoutExtension(url); List <ExcelStateObj> excelList = ExcelFunction.ReadExcel(url); for (int i = 0; i < excelList.Count; i++) { excelDict[excelList[i].ExcelName] = excelList[i]; } List <string> list = new List <string>(excelDict.Keys); tables = list.ToArray(); currentTable = 0; //Debug.Log(excelDict.Count+"--"+tables.Length); }
public FunctionCompiler(ExcelFunction function, ParsingContext context) { Require.That(function).Named("function").IsNotNull(); Require.That(context).Named("context").IsNotNull(); Function = function; Context = context; }
private void readModel(string url, ExcelStateObj table) { if (string.IsNullOrEmpty(url)) { return; } table.ModelName = System.IO.Path.GetFileNameWithoutExtension(url); FileInfo fi = new FileInfo(url); string content = ExcelFunction.LoadFileStr(url); switch (fi.Extension) { case ".xml": case ".XML": case ".Xml": readModelXmlFile(content, table); break; case ".json": case ".JSON": case ".Json": readModelJsonFile(content, table); break; } }
private DateTime[] GetDate() { // ----------arrDateRange----------------------- 获取此工作表中的整个施工日期的数组(0-Based,数据类型为Date) Excel.Range rg_AllDay = default(Excel.Range); //注意此数组元素的类型为Object,而且其第一个元素的下标值有可能是(1,1) short startColNum = ColNum_FirstData_Displacement; short endColNum = (short)(F_arrBottomRightCorner[1]); rg_AllDay = F_shtMonitorData.Rows[RowNumForDate].Range(F_shtMonitorData.Cells[1, startColNum], F_shtMonitorData.Cells[1, endColNum]); DateTime[] arrDateRange = null; arrDateRange = ExcelFunction.ConvertRangeDataToVector <DateTime>(rg_AllDay); // DateTime Dt = default(DateTime); try { Dictionary <DateTime, int> dicDate = new Dictionary <DateTime, int>(); foreach (DateTime tempLoopVar_Dt in arrDateRange) { Dt = tempLoopVar_Dt; dicDate.Add(Dt, 0); } } catch (Exception ex) { MessageBox.Show("工作表中的日期字段出错,出错的日期为:" + Dt.ToString("yyyy/MM/dd") + " 。请检查工作表!" + "\r\n" + ex.Message + "\r\n" + "报错位置:" + ex.TargetSite.Name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } return(arrDateRange); }
/// <summary> /// Default constructor for the <see cref="FunctionCompiler"/>. /// </summary> /// <param name="function">The <see cref="ExcelFunction"/> to compile.</param> public FunctionCompiler(ExcelFunction function) { if (function == null) { throw new ArgumentNullException(nameof(function)); } this.Function = function; }
public IfFunctionCompiler(ExcelFunction function, ParsingContext context) : base(function, context) { Require.That(function).Named("function").IsNotNull(); if (!(function is If)) { throw new ArgumentException("function must be of type If"); } }
private FunctionCompiler GetCompilerByType(ExcelFunction function) { var funcType = function.GetType(); if (_specialCompilers.ContainsKey(funcType)) { return(_specialCompilers[funcType]); } return(new DefaultCompiler(function, _context)); }
public virtual FunctionCompiler Create(ExcelFunction function) { if (function.IsLookupFuction) { return(new LookupFunctionCompiler(function)); } if (function.IsErrorHandlingFunction) { return(new ErrorHandlingFunctionCompiler(function)); } return(new DefaultCompiler(function)); }
public virtual FunctionCompiler Create(ExcelFunction function) { if (function.IsLookupFuction) { return(new LookupFunctionCompiler(function, _context)); } if (function.IsErrorHandlingFunction) { return(new ErrorHandlingFunctionCompiler(function, _context)); } return(GetCompilerByType(function)); }
public void FunctionTest(ExcelFunction function) { Regex regex = new Regex("^[-a-zA-Z0-9_' ]+$"); foreach (string argument in function.RequiredArguments) { MStringAssert.Matches(argument, regex); } foreach (string argument in function.OptionalArguments) { MStringAssert.Matches(argument, regex); } }
/// <summary> /// 当选择的数据工作表发生变化时引发 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks></remarks> public void listSheetsName_SelectedIndexChanged(object sender, EventArgs e) { this.F_shtMonitorData = (Excel.Worksheet)listSheetsName.SelectedValue; //wkbkData.Worksheets(listSheetsName.SelectedItem) string[] arrPointsTag = null; //此工作表中的测点的编号列表 //测点编号所在的起始行与末尾行 int startRow = RowNum_FirstData_WithoutDate; int endRow = F_shtMonitorData.UsedRange.Rows.Count; int endColumn = F_shtMonitorData.UsedRange.Columns.Count; F_arrBottomRightCorner = new[] { endRow, endColumn }; //'进行操作的工作表的UsedRange的右下角的行号与列号 if (endRow >= startRow) { Excel.Range rg_PointsTag = F_shtMonitorData.Columns[ColNum_PointsTag].Range(F_shtMonitorData.Cells[startRow, 1], F_shtMonitorData.Cells[endRow, 1]); arrPointsTag = ExcelFunction.ConvertRangeDataToVector <string>(rg_PointsTag); //------------ 将编号列表的每一个值与其对应的行号添加到字典dicPointTag_RowNum中 short TagsCount = (short)arrPointsTag.Length; LstbxDisplayAndItem[] arrPoints = new LstbxDisplayAndItem[TagsCount - 1 + 1]; int add = 0; int i = 0; foreach (string tag in arrPointsTag) { //在Excel数据表中,每一个监测点位的Tag所在的行号。 short RowNumToPointsTag = (short)(startRow + add); arrPoints[i] = new LstbxDisplayAndItem(tag, startRow + add); add++; i++; } //---------------------- 将编号列表的所有值显示在窗口的测点列表中 ListBoxPointsName.DisplayMember = LstbxDisplayAndItem.DisplayMember; ListBoxPointsName.ValueMember = LstbxDisplayAndItem.ValueMember; ListBoxPointsName.DataSource = arrPoints; //.Items.Clear() //.Items.AddRange(arr) //.SelectedIndex = 0 '选择列表中的第一项 // btnGenerate.Enabled = true; } else //说明此表中的监测数据行数小于1 { ListBoxPointsName.DataSource = null; //ListPointsName.Items.Clear() MessageBox.Show("此工作表没有合法数据(数据行数小于1行),请选择合适的工作表", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); F_shtMonitorData = null; btnGenerate.Enabled = false; } }
/// <summary> /// 开始绘制开挖剖面图的Chart对象 /// </summary> /// <returns>进行绘图的Chart对象的高度值,以磅为单位,可以用来确定Excel Application的高度值</returns> /// <remarks>绘图时,标高值与Excel中的Y坐标值的对应关系: /// 在程序中,定义了eleTop变量(以米为单位)与F_sngTopRef变量(以磅为单位), /// 它们指示的是此基坑区域中,地下室顶板的标高值与其在Excel绘图中对应的Y坐标值</remarks> private Microsoft.Office.Interop.Excel.Chart DrawChart(Microsoft.Office.Interop.Excel.Worksheet DrawingSheet, List <clsData_ProcessRegionData> SelectedRegion) { Microsoft.Office.Interop.Excel.Application DrawingApp = DrawingSheet.Application; DrawingApp.ScreenUpdating = false; DrawingApp.Caption = "开挖标高图"; //---------------- 创建一个新的,进行绘图的Chart对象 ------------------------------- Excel.Chart DrawingChart = default(Excel.Chart); DrawingChart = DrawingSheet.Shapes.AddChart(Top: 0, Left: 0).Chart; string TemplatePath = System.IO.Path.Combine(System.Convert.ToString(My.Settings.Default.Path_Template), Constants.FolderOrFileName.File_Template.Chart_Elevation); DrawingChart.Parent.Activate(); DrawingChart.ApplyChartTemplate(TemplatePath); this.F_Textbox_Info = DrawingChart.Shapes.Item(1).TextFrame2; DrawingChart.ChartTitle.Text = "开挖标高图"; // Microsoft.Office.Interop.Excel.SeriesCollection src = DrawingChart.SeriesCollection(); for (short i = 0; i <= 1 - src.Count; i++) //确保Chart中至少有两个数据系列 { src.NewSeries(); } // ----------------------- 设置绘图及Excel窗口的尺寸 ---------------------------- double ChartHeight = 400; double InsideLeft = 60; double InsideRight = 20; double LeastWidth_Chart = 500; double LeastWidth_Column = 100; // double ChartWidth = LeastWidth_Chart; double insideWidth = LeastWidth_Chart - InsideLeft - InsideRight; // ChartWidth = GetChartWidth(DrawingChart, SelectedRegion.Count, LeastWidth_Chart, LeastWidth_Column, InsideLeft + InsideRight, ref insideWidth); ChartSize Size_Chart_App = new ChartSize(ChartHeight, ChartWidth, 26, 9); ExcelFunction.SetLocation_Size(Size_Chart_App, DrawingChart, DrawingChart.Application, true); //With DrawingChart.PlotArea // .InsideLeft = InsideLeft // .InsideWidth = insideWidth //End With // -------------------------------------------------- return(DrawingChart); }
/// <summary> /// 找出某工作表在数据库集合中所对应的那一项,如果没有对应项,则返回Nothing /// </summary> /// <param name="DataSheet">要进行匹配的Excel工作表</param> /// <param name="DatasheetCollection">要进行搜索的数据库集合。</param> private DataSheet CorrespondingInCollection(Worksheet DataSheet, List <DataSheet> DatasheetCollection) { DataSheet dtSheet = null; foreach (DataSheet dbSheet in F_DbSheets) { if (ExcelFunction.SheetCompare(dbSheet.WorkSheet, DataSheet)) { dtSheet = dbSheet; break; } } return(dtSheet); }
public override CompileResult Execute(IEnumerable <FunctionArgument> arguments, ParsingContext context) { ValidateArguments(arguments, 2); var funcNum = ArgToInt(arguments, 0); if (context.Scopes.Current.Parent != null && context.Scopes.Current.Parent.IsSubtotal) { return(CreateResult(0d, DataType.Decimal)); } var actualArgs = arguments.Skip(1); ExcelFunction function = null; function = GetFunctionByCalcType(funcNum); return(function.Execute(actualArgs, context)); }
/// <summary> /// 绘制开挖工况的位置线 /// </summary> /// <param name="Cht"></param> /// <param name="WorkingStage"></param> /// <remarks></remarks> private void DrawWorkingStage(Excel.Chart Cht, List <clsData_WorkingStage> WorkingStage) { Excel.Axis AX = Cht.Axes(Excel.XlAxisType.xlCategory) as Excel.Axis; string[] arrLineName = new string[WorkingStage.Count - 1 + 1]; string[] arrTextName = new string[WorkingStage.Count - 1 + 1]; Excel.Chart with_1 = Cht; try { int i = 0; foreach (clsData_WorkingStage WS in WorkingStage) { // ------------------------------------------------------------------------------------------- Excel.Shape shpLine = with_1.Shapes.AddLine(BeginX: 0, BeginY: Cht.PlotArea.InsideTop, EndX: 0, EndY: 75); shpLine.Line.Weight = (float)(1.2F); //.EndArrowheadStyle = Microsoft.Office.Core.MsoArrowheadStyle.msoArrowheadStealth //.EndArrowheadLength = Microsoft.Office.Core.MsoArrowheadLength.msoArrowheadLengthMedium //.EndArrowheadWidth = Microsoft.Office.Core.MsoArrowheadWidth.msoArrowheadWidthMedium shpLine.Line.DashStyle = Microsoft.Office.Core.MsoLineDashStyle.msoLineDashDot; shpLine.Line.ForeColor.RGB = Information.RGB(255, 0, 0); // ExcelFunction.setPositionInChart(shpLine, AX, WS.ConstructionDate.ToOADate()); // ------------------------------------------------------------------------------------------- float TextWidth = 25; float textHeight = 10; Excel.Shape shpText = default(Excel.Shape); shpText = Cht.Shapes.AddTextbox(Orientation: Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, Left: shpLine.Left - TextWidth / 2, Top: shpLine.Top - textHeight, Height: ref textHeight, Width: ref TextWidth); ExcelFunction.FormatTextbox_Tag(TextFrame: shpText.TextFrame2, Text: WS.Description, HorizontalAlignment: Microsoft.Office.Core.MsoParagraphAlignment.msoAlignCenter); // ------------------------------------------------------------------------------------------- arrLineName[i] = shpLine.Name; arrTextName[i] = shpText.Name; i++; } Excel.Shape shp1 = Cht.Shapes.Range[arrLineName].Group(); Excel.Shape shp2 = Cht.Shapes.Range[arrTextName].Group(); Cht.Shapes.Range[new[] { shp1.Name, shp2.Name }].Group(); } catch (Exception ex) { MessageBox.Show("设置开挖工况位置出现异常。" + "\r\n" + ex.Message + "\r\n" + "报错位置:" + ex.TargetSite.Name, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public string GetExportXml() { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement root = XmlTool.NewXmlNode(doc, doc, ExportName); for (int i = 0; i < Rows.Length; i++) { EditorRow row = _Rows[i]; if (row == null || !row.CanExport) { continue; } System.Xml.XmlElement xe = row.GetExportXml(doc); XmlTool.SetParentXmlNode(root, xe); } return(ExcelFunction.ConvertXmlToString(doc)); }
private FunctionCompiler GetCompilerByType(ExcelFunction function) { var funcType = function.GetType(); if (_specialCompilers.ContainsKey(funcType)) { return(_specialCompilers[funcType]); } else if (function.IsLookupFuction) { return(new LookupFunctionCompiler(function, _context)); } else if (function.IsErrorHandlingFunction) { return(new ErrorHandlingFunctionCompiler(function, _context)); } return(new DefaultCompiler(function, _context)); }
private void DrawExport() { if (selectTable == null) { return; } if (GUILayout.Button("ExportJson")) { string wUrl = EditorUtility.SaveFilePanel("ExportJson", "", "" + "new File.json", "json"); ExcelFunction.WriteLocal(selectTable.GetExportJson(), 0, wUrl); } EditorGUILayout.Space(); if (GUILayout.Button("ExportXml")) { string wUrl = EditorUtility.SaveFilePanel("ExportXml", "", "" + "new File.xml", "xml"); ExcelFunction.WriteLocal(selectTable.GetExportXml(), 0, wUrl); } }
/// <summary> /// 将项目文件中的工作表添加到组合列表框中 /// </summary> /// <param name="cmbx">进行添加的组合列表框</param> /// <param name="destinationSheet">要添加到组合列表框中的工作表对象</param> /// <remarks></remarks> private void SheetToComboBox(ComboBox cmbx, Worksheet destinationSheet) { LstbxDisplayAndItem lstbxItem = default(LstbxDisplayAndItem); Worksheet sht = default(Worksheet); ComboBox with_1 = cmbx; foreach (LstbxDisplayAndItem tempLoopVar_lstbxItem in with_1.Items) { lstbxItem = tempLoopVar_lstbxItem; if (!lstbxItem.Value.Equals(LstbxDisplayAndItem.NothingInListBox.None)) { //有可能会出现列表中的项目不能转换为工作表对象的情况,比如第一项"" sht = (Worksheet)lstbxItem.Value; if (ExcelFunction.SheetCompare(sht, destinationSheet)) { with_1.SelectedItem = lstbxItem; break; } } } }
//public void AppendToScriptBuffer(byte[] scriptBytes) //{ // Int32 byteCount = _scriptBuffer.Length + scriptBytes.Length; // byte[] scriptBuffer = new byte[byteCount]; // Buffer.BlockCopy(_scriptBuffer, 0, scriptBuffer, 0, _scriptBuffer.Length); // Buffer.BlockCopy(scriptBytes, 0, scriptBuffer, _scriptBuffer.Length, scriptBytes.Length); // _scriptBuffer = scriptBuffer; //} private bool _ParsePropertiesScriptTable(byte[] data, ref int offset) { ExcelFunctions = new List <ExcelFunction>(); while (offset <= data.Length) { if (_CheckToken(data, offset, Token.dneh)) { return(true); } ExcelFunction excelScript = new ExcelFunction(); if (!_ParsePropertiesScript(data, ref offset, ref excelScript)) { return(false); } ExcelFunctions.Add(excelScript); } return(false); }
/// <summary> /// 初始化参数 /// </summary> private void Initialize() { sConFilePath = ConfigurationSettings.AppSettings["Config.FilePath"]; sLogFilePath = ConfigurationSettings.AppSettings["Log.FilePath"]; sServerName = ConfigurationSettings.AppSettings["ServerName"]; sSqlStr = ConfigurationSettings.AppSettings["SqlStr"]; iDataRefrTimes = int.Parse(ConfigurationSettings.AppSettings["DataRefrTimes"]); iSqlRefrTimes = int.Parse(ConfigurationSettings.AppSettings["SqlRefrTimes"]); bReConnect = bool.Parse(ConfigurationSettings.AppSettings["bReConnect"]); iReConnectTimes = int.Parse(ConfigurationSettings.AppSettings["ReConnectTimes"]); opcKepClient = new OPCClient(sLogFilePath); string[] sConFilePaths = sConFilePath.Split(new char[] { ';' }); foreach (string sConFilePath in sConFilePaths) { string[] sFlieNames = sConFilePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); string sFlieName = sFlieNames[sFlieNames.Length - 1]; sFlieName = sFlieName.Replace(".xlsx", ""); OPCItemsStruct OPCItemsStrt = new OPCItemsStruct(); OPCItemsStrt.sGroupName = sFlieName; DataSet dsOPCGroup = ExcelFunction.ExcelRead(sConFilePath); DataTable dtOPCGroup = dsOPCGroup.Tables[0]; int iRowCounts = dtOPCGroup.Rows.Count; OPCItemsStrt.sItems = new string[iRowCounts]; for (int i = 0; i < iRowCounts; i++) { if (dtOPCGroup.Rows[i][0] is System.DBNull == false) { OPCItemsStrt.sItems[i] = sFlieName + "." + dtOPCGroup.Rows[i][0].ToString(); } } lOPCItemsStrt.Add(OPCItemsStrt); } }
// 开始具体的调试操作 private static void DoSomething(Application app) { Worksheet sht = app.ActiveSheet; Workbook wkbk = app.ActiveWorkbook; var rg = app.InputBox("选择第二张表格中的区域(包括第一个表格中的小计行)", Type: 8) as Range; if (rg != null) { int?lastRow = 0; lastRow = ExcelFunction.GetRowNum(app, "最后一行数据的行号:"); if (lastRow != null) { var sumupRow = rg.Rows[1] as Range; Range indexColumn = sht.Range[rg.Cells[2, 1], rg.Cells[rg.Rows.Count - 1, 1]] as Range; var startRow = sumupRow.Row + 1; var dataRowsCount = indexColumn.Count; // SumRowHandler.InsertSumupRow(app, sumupRow: sumupRow, indexColumn: indexColumn, startRow: startRow, dataRowsCount: dataRowsCount, lastRow: lastRow.Value); } else { MessageBox.Show(@"请输入一个数值"); } } return; // SumRowHandler.InsertSumupRow(app, sht.Range["A36:Q36"], sht.Range["A37:A64"], 37, 28, 1010 + 7); return; var slpHdl = new SlopeInfoHandler(app); slpHdl.Execute(containsHeader: true); }
public override bool Handle(string funcName, IEnumerable <Expression> children, ParsingContext context, out ExcelFunction function) { function = null; if (funcName.Contains(":OFFSET")) { var functionCompilerFactory = new FunctionCompilerFactory(context.Configuration.FunctionRepository, context); var startRange = funcName.Split(':')[0]; var c = context.Scopes.Current; var resultRange = context.ExcelDataProvider.GetRange(c.Address.Worksheet, c.Address.FromRow, c.Address.FromCol, startRange); var rangeOffset = new RangeOffset { StartRange = resultRange }; var compiler = functionCompilerFactory.Create(new Offset()); children.First().Children.First().IgnoreCircularReference = true; var compileResult = compiler.Compile(children); rangeOffset.EndRange = compileResult.Result as ExcelDataProvider.IRangeInfo; function = rangeOffset; return(true); } return(false); }
private static bool _ParsePropertiesScript(byte[] data, ref int offset, ref ExcelFunction excelScript) { ExcelFunction.Parameter parameter = new ExcelFunction.Parameter(); // token and version checks if (!_CheckToken(data, ref offset, Token.mysh)) return false; UInt32 version = FileTools.ByteArrayToUInt32(data, ref offset); if (version != Token.MyshVersion) return false; // general parameter values int charCount = FileTools.ByteArrayToInt32(data, ref offset); if (charCount >= 0x1000) return false; parameter.Name = FileTools.ByteArrayToStringASCII(data, ref offset, charCount); parameter.Unknown = FileTools.ByteArrayToUInt32(data, ref offset); // what kind of parameter is it parameter.TypeId = FileTools.ByteArrayToUInt32(data, ref offset); int paramLength; switch (parameter.TypeId) { case 0x38: // 56 // "nPowerChange" from TCv4 Skills paramLength = 4; break; case 0x39: // 57 // oldstats, x, sel, dmgtype, ? paramLength = 4; break; case 0x3C: // 60 // dam, ? paramLength = 5; break; case 0x41: // 65 // dmg_elec, dmg_fire, etc paramLength = 8; break; default: Debug.Assert(false, "Unknown MYSH TypeId = " + parameter.TypeId); return false; } parameter.TypeValues = FileTools.ByteArrayToInt32Array(data, ref offset, paramLength); excelScript.Parameters.Add(parameter); if (parameter.TypeId != 0x41) return true; // only 0x41 has paramaters and a script values block following it // get remaining parameters int paramCount = parameter.TypeValues[5]; for (int i = 0; i < paramCount; i++) { if (!_ParsePropertiesScript(data, ref offset, ref excelScript)) return false; } // the actual script values int valuesByteCount = FileTools.ByteArrayToInt32(data, ref offset); if (valuesByteCount <= 0) return false; excelScript.ScriptByteCode = new byte[valuesByteCount]; Buffer.BlockCopy(data, offset, excelScript.ScriptByteCode, 0, valuesByteCount); offset += valuesByteCount; return true; }
//public void AppendToScriptBuffer(byte[] scriptBytes) //{ // Int32 byteCount = _scriptBuffer.Length + scriptBytes.Length; // byte[] scriptBuffer = new byte[byteCount]; // Buffer.BlockCopy(_scriptBuffer, 0, scriptBuffer, 0, _scriptBuffer.Length); // Buffer.BlockCopy(scriptBytes, 0, scriptBuffer, _scriptBuffer.Length, scriptBytes.Length); // _scriptBuffer = scriptBuffer; //} private bool _ParsePropertiesScriptTable(byte[] data, ref int offset) { ExcelFunctions = new List<ExcelFunction>(); while (offset <= data.Length) { if (_CheckToken(data, offset, Token.dneh)) return true; ExcelFunction excelScript = new ExcelFunction(); if (!_ParsePropertiesScript(data, ref offset, ref excelScript)) return false; ExcelFunctions.Add(excelScript); } return false; }
private bool _ParseCSV(byte[] csvBytes, FileManager fileManager, Dictionary<String, ExcelFile> csvExcelFiles) { // function setup int stringBufferOffset = 0; int integerBufferOffset = 1; bool isProperties = (StringId == "PROPERTIES" || StringId == "_TCv4_PROPERTIES"); ObjectDelegator objectDelegator; OutputAttribute[] excelAttributes; bool needOutputAttributes = true; if (fileManager == null || !fileManager.DataFileDelegators.ContainsKey(StringId)) { FieldInfo[] fieldInfos = DataType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fieldInfos = fieldInfos.OrderBy(f => f.MetadataToken).ToArray(); // order by defined order - GetFields does not guarantee ordering objectDelegator = new ObjectDelegator(fieldInfos); excelAttributes = new OutputAttribute[fieldInfos.Length]; } else { objectDelegator = fileManager.DataFileDelegators[StringId]; excelAttributes = new OutputAttribute[objectDelegator.FieldCount]; } String[][] tableRows; if (csvBytes == null) { tableRows = _csvTable; } else { // get columns int offset = 0; int colCount = 1; while (csvBytes[offset++] != '\n') if (csvBytes[offset] == CSVDelimiter) colCount++; tableRows = FileTools.CSVToStringArray(csvBytes, colCount, CSVDelimiter); } int rowCount = tableRows.Length; String[] columns = tableRows[0]; if (isProperties) { ExcelFunctions = new List<ExcelFunction>(); _scriptBuffer = new byte[1]; // properties is weird - do this just to ensure 100% byte-for-byte accuracy } // parse file header - could use Regex here - but don't think that'd but faster, in fact, probably a lot slower(?) - meh // format: %s(%s) // first %s = StringId, second %s = FileHeader as String String fileHeader = columns[0]; int fileHeaderStart = fileHeader.IndexOf("(") + 1; int fileHeaderEnd = fileHeader.IndexOf(")"); String fileHeaderStr = fileHeader.Substring(fileHeaderStart, fileHeaderEnd - fileHeaderStart); _excelFileHeader = FileTools.StringToObject<ExcelHeader>(fileHeaderStr, ",", FileHeaderFields); String strId = fileHeader.Substring(0, fileHeader.IndexOf("(")).Trim(); // asking for exception lol Debug.Assert(strId == StringId); // Parse the tableRows bool failedParsing = false; Rows = new List<Object>(); for (int row = 1; row < rowCount; row++) { int col = -1; int csvCol = 0; Object rowInstance = Activator.CreateInstance(DataType); foreach (ObjectDelegator.FieldDelegate fieldDelegate in objectDelegator) { col++; if (needOutputAttributes) excelAttributes[col] = GetExcelAttribute(fieldDelegate.Info); OutputAttribute excelAttribute = excelAttributes[col]; // columns not present if (!columns.Contains(fieldDelegate.Name)) { // create row header object if (fieldDelegate.FieldType == typeof(RowHeader)) { String headerString = tableRows[row][csvCol++]; RowHeader rowHeader = FileTools.StringToObject<RowHeader>(headerString, ",", RowHeaderFields); objectDelegator[fieldDelegate.Name, rowInstance] = rowHeader; continue; } // assign default values MarshalAsAttribute arrayMarshal = null; Array arrayInstance = null; if (fieldDelegate.FieldType.BaseType == typeof(Array)) { arrayMarshal = (MarshalAsAttribute)fieldDelegate.Info.GetCustomAttributes(typeof(MarshalAsAttribute), false).First(); arrayInstance = (Array)Activator.CreateInstance(fieldDelegate.FieldType, arrayMarshal.SizeConst); objectDelegator[fieldDelegate.Name, rowInstance] = arrayInstance; } else if (fieldDelegate.FieldType == typeof(String)) { objectDelegator[fieldDelegate.Name, rowInstance] = String.Empty; } // assign constant non-zero values if (excelAttribute == null || excelAttribute.ConstantValue == null) continue; if (fieldDelegate.FieldType.BaseType == typeof(Array)) { Debug.Assert(arrayInstance != null, "arrayInstance == null"); Debug.Assert(arrayMarshal != null, "arrayMarshal == null"); for (int i = 0; i < arrayMarshal.SizeConst; i++) { arrayInstance.SetValue(excelAttribute.ConstantValue, i); } } else { objectDelegator[fieldDelegate.Name, rowInstance] = excelAttribute.ConstantValue; } continue; } // columns present String value = tableRows[row][csvCol++]; if (fieldDelegate.Name == "code") { int code = (StringId == "REGION") ? int.Parse(value) : StringToCode(value); if (fieldDelegate.FieldType == typeof(short)) { objectDelegator[fieldDelegate.Name, rowInstance] = (short)code; } else { objectDelegator[fieldDelegate.Name, rowInstance] = code; } continue; } bool isArray = (fieldDelegate.FieldType.BaseType == typeof(Array)); bool isEnum = (fieldDelegate.FieldType.BaseType == typeof(Enum)); if (excelAttribute != null) { if (excelAttribute.IsTableIndex && fileManager != null) { int arraySize = 1; if (isArray) { MarshalAsAttribute arrayMarshal = (MarshalAsAttribute)fieldDelegate.Info.GetCustomAttributes(typeof(MarshalAsAttribute), false).First(); arraySize = arrayMarshal.SizeConst; Debug.Assert(arraySize > 0); } String[] indexStrs = value.Split(new[] { ',' }); Int32[] rowIndexValues = new int[arraySize]; for (int i = 0; i < arraySize; i++) rowIndexValues[i] = -1; int maxElements = indexStrs.Length; if (maxElements > arraySize) { Debug.WriteLine(String.Format("{0}: Loss of array elements detected. row = {1}, col = {2}.", StringId, row, col)); maxElements = arraySize; } for (int i = 0; i < maxElements; i++) { value = indexStrs[i]; if (value == "-1") continue; String tableStringId = excelAttribute.TableStringId; bool hasCodeColumn = fileManager.DataTableHasColumn(tableStringId, "code"); if (value.Length == 0 && hasCodeColumn) continue; //LEVEL references multiple blank TREASURE row index values - all appear to be empty rows though, so meh... //Debug.Assert(!String.IsNullOrEmpty(value)); int isNegative = 1; if (value.Length > 0 && value[0] == '-') { isNegative = -1; value = value.Substring(1, value.Length - 1); } int rowIndex = -1; ExcelFile relatedExcel = null; if (csvExcelFiles != null && csvExcelFiles.TryGetValue(tableStringId, out relatedExcel)) { rowIndex = relatedExcel._GetRowIndexFromValue(value, hasCodeColumn ? "code" : null); } if (relatedExcel == null) { if (hasCodeColumn && value.Length <= 4) { int code = StringToCode(value); rowIndex = fileManager.GetExcelRowIndexFromStringId(tableStringId, code, "code"); } else if (fileManager.DataTableHasColumn(tableStringId, "name")) { rowIndex = fileManager.GetExcelRowIndexFromStringId(tableStringId, value, "name"); } else { rowIndex = fileManager.GetExcelRowIndex(tableStringId, value); } } rowIndexValues[i] = rowIndex * isNegative; } if (isArray) { objectDelegator[fieldDelegate.Name, rowInstance] = rowIndexValues; } else { objectDelegator[fieldDelegate.Name, rowInstance] = rowIndexValues[0]; } continue; } if (excelAttribute.IsStringOffset) { if (_stringBuffer == null) _stringBuffer = new byte[1024]; if (String.IsNullOrEmpty(value)) { objectDelegator[fieldDelegate.Name, rowInstance] = -1; continue; } objectDelegator[fieldDelegate.Name, rowInstance] = stringBufferOffset; FileTools.WriteToBuffer(ref _stringBuffer, ref stringBufferOffset, FileTools.StringToASCIIByteArray(value)); stringBufferOffset++; // \0 continue; } if (excelAttribute.IsScript) { if ((fileManager == null && value == "0") || value == "") { objectDelegator[fieldDelegate.Name, rowInstance] = 0; continue; } if (_scriptBuffer == null) { _scriptBuffer = new byte[1024]; _scriptBuffer[0] = 0x00; } int[] scriptByteCode; if (fileManager != null) { ExcelScript excelScript = new ExcelScript(fileManager); scriptByteCode = excelScript.Compile(value, null, StringId, row, col, fieldDelegate.Name); } else { string[] splitValue = value.Split(','); int count = splitValue.Length; scriptByteCode = new int[count]; for (int i = 0; i < count; i++) { scriptByteCode[i] = int.Parse(splitValue[i]); } } objectDelegator[fieldDelegate.Name, rowInstance] = integerBufferOffset; FileTools.WriteToBuffer(ref _scriptBuffer, ref integerBufferOffset, scriptByteCode.ToByteArray()); continue; } if (excelAttribute.IsSecondaryString) { if (SecondaryStrings == null) SecondaryStrings = new List<String>(); if (value == "") { objectDelegator[fieldDelegate.Name, rowInstance] = -1; continue; } if (!SecondaryStrings.Contains(value)) { SecondaryStrings.Add(value); } objectDelegator[fieldDelegate.Name, rowInstance] = SecondaryStrings.IndexOf(value); continue; } if (excelAttribute.IsBitmask) { if (fieldDelegate.FieldType == typeof(UInt32)) { objectDelegator[fieldDelegate.Name, rowInstance] = UInt32.Parse(value); continue; } Object enumVal; try { enumVal = Enum.Parse(fieldDelegate.FieldType, value); } catch (Exception) { String[] enumStrings = value.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); String[] enumNames = Enum.GetNames(fieldDelegate.FieldType); String enumString = String.Empty; String enumSeperator = String.Empty; foreach (String enumStr in enumStrings) { if (!enumNames.Contains(enumStr)) { Debug.WriteLine(String.Format("{0}: bitfield name '{1}' not found.", StringId, enumStr)); continue; } enumString += enumSeperator + enumStr; enumSeperator = ","; } enumVal = enumString == "" ? 0 : Enum.Parse(fieldDelegate.FieldType, enumString); } objectDelegator[fieldDelegate.Name, rowInstance] = enumVal; continue; } } try { Object objValue; if (isArray) { if (fieldDelegate.FieldType == typeof(Int32[])) { objValue = FileTools.StringToArray<Int32>(value, ","); } else { Type elementType = fieldDelegate.FieldType.GetElementType(); if (elementType.BaseType == typeof(Enum)) { String[] enumStrs = value.Split(new[] { ',' }, StringSplitOptions.None); Array enumsArray = Array.CreateInstance(elementType, enumStrs.Length); int i = 0; foreach (String enumStr in enumStrs) { enumsArray.SetValue(Enum.Parse(elementType, enumStr), i++); } objValue = enumsArray; } else { throw new NotImplementedException("if (fieldInfo.FieldType.BaseType == typeof(Array)) :: Type = " + elementType.BaseType); } } objectDelegator[fieldDelegate.Name, rowInstance] = objValue; } else if (isEnum) { object enumVal = Enum.Parse(fieldDelegate.FieldType, value); objectDelegator[fieldDelegate.Name, rowInstance] = enumVal; } else { objValue = FileTools.StringToObject(value, fieldDelegate.FieldType); objectDelegator[fieldDelegate.Name, rowInstance] = objValue; } } catch (Exception e) { Console.WriteLine("Critical Parsing Error: " + e); failedParsing = true; break; } } if (failedParsing) break; needOutputAttributes = false; // applicable only for Unit type; items, missiles, monsters, objects, players if (Attributes.HasStats) { if (StatsBuffer == null) StatsBuffer = new byte[rowCount - 1][]; String value = tableRows[row][csvCol]; String[] stringArray = value.Split(','); byte[] byteArray = new byte[stringArray.Length]; for (int i = 0; i < byteArray.Length; i++) { byteArray[i] = Byte.Parse(stringArray[i]); } StatsBuffer[row - 1] = byteArray; } // properties has extra Scripts stuffs // yea, this is a bit messy, but it's a single table only and mostly done out of curiosity if (isProperties) { String value = tableRows[row][csvCol]; String[] scripts = value.Split('\n'); ExcelFunction excelScript = new ExcelFunction(); if (scripts.Length > 1) { ExcelFunctions.Add(excelScript); } int i = 0; do { if (scripts.Length == 1) continue; i++; String[] values = scripts[i].Split(','); if (values.Length < 4) continue; // script parameters int typeValuesCount = values.Length - 3; ExcelFunction.Parameter parameter = new ExcelFunction.Parameter { Name = values[0], Unknown = UInt32.Parse(values[1]), TypeId = UInt32.Parse(values[2]), TypeValues = new int[typeValuesCount] }; for (int j = 0; j < typeValuesCount; j++) { parameter.TypeValues[j] = Int32.Parse(values[3 + j]); } excelScript.Parameters.Add(parameter); } while (i < scripts.Length - 1 - 2); // -2 for: last line is blank, and line before *might* be script values // last line will be script values if it exists if (i < scripts.Length - 2) { String[] values = scripts[++i].Split(','); int[] scriptValues = new int[values.Length]; for (int j = 0; j < values.Length; j++) { scriptValues[j] = Int32.Parse(values[j]); } excelScript.ScriptByteCode = scriptValues.ToByteArray(); } } Rows.Add(rowInstance); } // resize the integer and string buffers if they were used if (_stringBuffer != null) Array.Resize(ref _stringBuffer, stringBufferOffset); if (_scriptBuffer != null) Array.Resize(ref _scriptBuffer, integerBufferOffset); return HasIntegrity = true; }