protected FuncDrawOperation(Player player, Command cmd) : base(player) { string strFunc = cmd.Next(); if (string.IsNullOrWhiteSpace(strFunc)) { player.Message("&WEmpty function expression"); return; } if (strFunc.Length < 3) { player.Message("&WExpression is too short (should be like z=f(x,y))"); return; } strFunc = strFunc.ToLower(); _vaxis = GetAxis(SimpleParser.PreparseAssignment(ref strFunc)); _expression = SimpleParser.Parse(strFunc, GetVarArray(_vaxis)); Player.Message("Expression parsed as "+_expression.Print()); string scalingStr=cmd.Next(); _scaler = new Scaler(scalingStr); }
/// <summary>Adds a logical alias for the given CSS property to the given target. /// A numeric target, e.g. 1, means that inner index of this property, which is a set.</summary> protected void LogicalAlias(string name, ValueAxis axis, params int[] target) { DirectionAwareProperty alias = new DirectionAwareProperty(this, target); alias.Axis = axis; AddAlias(name, alias); }
/// <summary>Adds an alias for the given CSS property to the given target. /// A numeric target, e.g. 1, means that inner index of this property, which is a set.</summary> protected void Alias(string name, ValueAxis axis, params int[] target) { CssPropertyAlias alias = new CssPropertyAlias(this, target); alias.Axis = axis; AddAlias(name, alias); }
protected FuncDrawOperation(Player player, Command cmd) : base(player) { string strFunc = cmd.Next(); if (string.IsNullOrWhiteSpace(strFunc)) { player.Message("&WEmpty function expression"); return; } if (strFunc.Length < 3) { player.Message("&WExpression is too short (should be like z=f(x,y))"); return; } strFunc = strFunc.ToLower(); _vaxis = GetAxis(SimpleParser.PreparseAssignment(ref strFunc)); _expression = SimpleParser.Parse(strFunc, GetVarArray(_vaxis)); player.Message("Expression parsed as " + _expression.Print()); string scalingStr = cmd.Next(); _scaler = new Scaler(scalingStr); }
private static string[] GetVarArray(ValueAxis axis) { switch (axis) { case ValueAxis.Z: return new string[] {"x", "y"}; case ValueAxis.Y: return new string[] { "x", "z" }; case ValueAxis.X: return new string[] { "y", "z" }; } throw new ArgumentException("Unknown value axis direction "+axis+". This software is not released for use in spaces with dimension higher than three."); }
/// <summary>If this is a decimal, the raw decimal value. This is generally the main output. /// This overload explicitly tells it to use the vertical axis or not (e.g. when resolving %).</summary> public float GetDecimal(RenderableData context,ValueAxis axis){ // Create the width or height property: if(VerticalProperty==null){ CreateAxisProperties(); } CssProperty property=(axis==ValueAxis.Y) ? VerticalProperty : (axis==ValueAxis.X) ? HorizontalProperty : DepthProperty; property.RelativeTo=ValueRelativity.SelfDimensions; // Get decimal using them: return GetDecimal(context,property); }
private static string[] GetVarArray(ValueAxis axis) { switch (axis) { case ValueAxis.Z: return(new string[] { "x", "y" }); case ValueAxis.Y: return(new string[] { "x", "z" }); case ValueAxis.X: return(new string[] { "y", "z" }); } throw new ArgumentException("Unknown value axis direction " + axis + ". This software is not released for use in spaces with dimension higher than three."); }
public CartesianAxes AppendCartesianAxes() { CategoryAxis categoryAxis = this.AppendCategoryAxis(); ValueAxis valueAxis = this.AppendValueAxis(); categoryAxis.CrossingAxis = new CrossingAxis() { Val = valueAxis.AxisId.Val }; valueAxis.CrossingAxis = new CrossingAxis() { Val = categoryAxis.AxisId.Val }; return(new CartesianAxes(new OpenXmlChartAxisBase(categoryAxis), new OpenXmlChartAxisBase(valueAxis))); }
/// <summary>Loads a set of colour aliases for a given property name. E.g. name-r,name-g,name-b and name-a. /// The alias may also be mapped to a sub-index. It must be an empty string otherwise.</summary> protected void ColourAliases(string property, ValueAxis axis, int index) { if (index == -1) { Alias(property + "-r", axis, 0); Alias(property + "-g", axis, 1); Alias(property + "-b", axis, 2); Alias(property + "-a", axis, 3); } else { Alias(property + "-r", axis, index, 0); Alias(property + "-g", axis, index, 1); Alias(property + "-b", axis, index, 2); Alias(property + "-a", axis, index, 3); } }
private static Dictionary <DateTime, ValueAxis> GetDataFromRecord() { var data = new Dictionary <DateTime, ValueAxis>(); var text = RecordToFile.GetRecords(); if (text != null) { foreach (var keyValue in text) { var key = keyValue.Key; var value = ToDateTimeFormat(keyValue.Value.TimeSpended); var timeValue = DateTime.Parse(keyValue.Value.TimeSpended); data[key] = new ValueAxis(value, timeValue); } } return(data); }
/// <summary> /// Writes the initialization script. /// </summary> /// <param name="writer">The writer object.</param> public override void WriteInitializationScript(TextWriter writer) { var objectWriter = ClientSideObjectWriterFactory.Create(Id, "tChart", writer); objectWriter.Start(); SerializeData("chartArea", ChartArea.CreateSerializer().Serialize(), objectWriter); SerializeData("plotArea", PlotArea.CreateSerializer().Serialize(), objectWriter); SerializeTheme(objectWriter); SerializeData("title", Title.CreateSerializer().Serialize(), objectWriter); SerializeData("legend", Legend.CreateSerializer().Serialize(), objectWriter); SerializeSeries(objectWriter); SerializeData("seriesDefaults", SeriesDefaults.CreateSerializer().Serialize(), objectWriter); SerializeData("axisDefaults", AxisDefaults.CreateSerializer().Serialize(), objectWriter); SerializeData("categoryAxis", CategoryAxis.CreateSerializer().Serialize(), objectWriter); SerializeData("valueAxis", ValueAxis.CreateSerializer().Serialize(), objectWriter); SerializeData("xAxis", XAxis.CreateSerializer().Serialize(), objectWriter); SerializeData("yAxis", YAxis.CreateSerializer().Serialize(), objectWriter); SerializeTransitions(objectWriter); SerializeDataBinding(objectWriter); SerializeSeriesColors(objectWriter); SerializeData("tooltip", Tooltip.CreateSerializer().Serialize(), objectWriter); ClientEvents.SerializeTo(objectWriter); objectWriter.Complete(); base.WriteInitializationScript(writer); }
public ValueAxis Build() { var valueAxis = new ValueAxis(); valueAxis.AxisId = new AxisId { Val = this.Options.Id }; valueAxis.Scaling = new Scaling(); valueAxis.Scaling.Orientation = new Orientation { Val = this.Options.Orientation }; if (this.Options.MinMaxBounds.HasValue) { var minAxisValue = new MinAxisValue { Val = this.Options.MinMaxBounds.Value.MinValue }; var maxAxisValue = new MaxAxisValue { Val = this.Options.MinMaxBounds.Value.MaxValue }; valueAxis.Scaling.Append(minAxisValue); valueAxis.Scaling.Append(maxAxisValue); } if (this.Options.MinMaxUnits.HasValue) { var minorUnit = new MinorUnit { Val = this.Options.MinMaxUnits.Value.MinValue }; var majorUnit = new MajorUnit { Val = this.Options.MinMaxUnits.Value.MaxValue }; valueAxis.Append(minorUnit); valueAxis.Append(majorUnit); } valueAxis.Delete = new Delete { Val = false }; valueAxis.AxisPosition = new AxisPosition { Val = this.Options.AxisPosition }; if (this.Options.ShowMajorGridlines) { var majorGridlinesBuilder = new MajorGridlinesBuilder(this.Options.MajorGridlinesOptions); valueAxis.MajorGridlines = majorGridlinesBuilder.Build(); } if (this.Options.HasNumberingFormat) { valueAxis.NumberingFormat = new NumberingFormat { FormatCode = this.Options.FormatCode, SourceLinked = this.Options.SourceLinked }; } valueAxis.MajorTickMark = new MajorTickMark { Val = this.Options.MajorTickMark }; valueAxis.MinorTickMark = new MinorTickMark { Val = this.Options.MinorTickMark }; valueAxis.TickLabelPosition = new TickLabelPosition { Val = this.Options.TickLabelPosition }; if (this.Options.HasChartShapeProperties) { var chartShapePropertiesBuilder = new ChartShapePropertiesBuilder(this.Options.ChartShapePropertiesOptions); valueAxis.ChartShapeProperties = chartShapePropertiesBuilder.Build(); } if (this.Options.IsTextStylish) { valueAxis.TextProperties = new TextProperties(); valueAxis.TextProperties.BodyProperties = new BodyProperties() { Rotation = -60000000, UseParagraphSpacing = true, VerticalOverflow = TextVerticalOverflowValues.Ellipsis, Vertical = TextVerticalValues.Horizontal, Wrap = TextWrappingValues.Square, Anchor = TextAnchoringTypeValues.Center, AnchorCenter = true }; valueAxis.TextProperties.ListStyle = new ListStyle(); var para = new Paragraph(); para.ParagraphProperties = new ParagraphProperties(); var defrunprops = new DefaultRunProperties(); defrunprops.FontSize = 900; defrunprops.Bold = false; defrunprops.Italic = false; defrunprops.Underline = TextUnderlineValues.None; defrunprops.Strike = TextStrikeValues.NoStrike; defrunprops.Kerning = 1200; defrunprops.Baseline = 0; var schclr = new SchemeColor() { Val = SchemeColorValues.Text1 }; schclr.Append(new LuminanceModulation() { Val = 65000 }); schclr.Append(new LuminanceOffset() { Val = 35000 }); defrunprops.Append(new SolidFill() { SchemeColor = schclr }); defrunprops.Append(new LatinFont() { Typeface = "+mn-lt" }); defrunprops.Append(new EastAsianFont() { Typeface = "+mn-ea" }); defrunprops.Append(new ComplexScriptFont() { Typeface = "+mn-cs" }); para.ParagraphProperties.Append(defrunprops); para.Append(new EndParagraphRunProperties() { Language = System.Globalization.CultureInfo.CurrentCulture.Name }); valueAxis.TextProperties.Append(para); } valueAxis.CrossingAxis = new CrossingAxis { Val = this.Options.CrossingAxisVal }; if (this.Options.Crosses.HasValue) { valueAxis.Append(new Crosses { Val = this.Options.Crosses }); } else if (this.Options.CrossesAtVal.HasValue) { valueAxis.Append(new CrossesAt() { Val = this.Options.CrossesAtVal }); } valueAxis.Append(new CrossBetween { Val = this.Options.CrossBetween }); return(valueAxis); }
private ValueAxis AppendValueAxis() { ChartSpace chartSpace = this.chartPart.ChartSpace; Chart chart = chartSpace.GetFirstChild <Chart>() ?? chartSpace.AppendChild(new Chart()); PlotArea plotArea = chart.GetFirstChild <PlotArea>() ?? chart.AppendChild(new PlotArea()); uint id = plotArea.Elements <ValueAxis>().Select(axis => axis.AxisId.Val.Value).DefaultIfEmpty(417314071u).Max() + 1; ValueAxis valueAxis = plotArea.AppendChild( new ValueAxis() { AxisId = new AxisId() { Val = id }, Scaling = new Scaling() { Orientation = new Orientation() { Val = OrientationValues.MinMax } }, Delete = new Delete() { Val = false }, AxisPosition = new AxisPosition() { Val = AxisPositionValues.Left }, MajorGridlines = new MajorGridlines() { ChartShapeProperties = new ChartShapeProperties() { // TODO } }, NumberingFormat = new NumberingFormat() { FormatCode = "General", SourceLinked = true }, MajorTickMark = new MajorTickMark() { Val = TickMarkValues.None }, MinorTickMark = new MinorTickMark() { Val = TickMarkValues.None }, TickLabelPosition = new TickLabelPosition() { Val = TickLabelPositionValues.NextTo }, ChartShapeProperties = new ChartShapeProperties() .AppendChildFluent(new Drawing.NoFill()) .AppendChildFluent(new Drawing.Outline().AppendChildFluent(new Drawing.NoFill())) .AppendChildFluent(new Drawing.EffectList()), TextProperties = new TextProperties() { BodyProperties = new Drawing.BodyProperties(), ListStyle = new Drawing.ListStyle() } .AppendChildFluent( new Drawing.Paragraph() { ParagraphProperties = new Drawing.ParagraphProperties().AppendChildFluent( new Drawing.DefaultRunProperties() { FontSize = 1197, Bold = false, Italic = false, Underline = Drawing.TextUnderlineValues.None, Strike = Drawing.TextStrikeValues.NoStrike, Kerning = 1200, Baseline = 0 } .AppendChildFluent( new Drawing.SolidFill() { SchemeColor = new Drawing.SchemeColor() { Val = Drawing.SchemeColorValues.Text1 } .AppendChildFluent(new Drawing.LuminanceModulation() { Val = 65000 }) .AppendChildFluent(new Drawing.LuminanceOffset() { Val = 35000 }) } ) .AppendChildFluent(new Drawing.LatinFont() { Typeface = "+mn-lt" }) .AppendChildFluent(new Drawing.EastAsianFont() { Typeface = "+mn-ea" }) .AppendChildFluent(new Drawing.ComplexScriptFont() { Typeface = "+mn-cs" }) ) } ) } .AppendChildFluent(new Crosses() { Val = CrossesValues.AutoZero }) .AppendChildFluent(new CrossBetween() { Val = CrossBetweenValues.Between }) ); return(valueAxis); }
private static void InsertChartInSpreadsheet(string docName, string worksheetName, string title, Dictionary <string, int> data) { // Open the document for editing. using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true)) { IEnumerable <Sheet> sheets = document.WorkbookPart.Workbook.Descendants <Sheet>(). Where(s => s.Name == worksheetName); if (sheets.Count() == 0) { // The specified worksheet does not exist. return; } WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id); // Add a new drawing to the worksheet. DrawingsPart drawingsPart = worksheetPart.AddNewPart <DrawingsPart>(); worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing() { Id = worksheetPart.GetIdOfPart(drawingsPart) }); worksheetPart.Worksheet.Save(); // Add a new chart and set the chart language to English-US. ChartPart chartPart = drawingsPart.AddNewPart <ChartPart>(); chartPart.ChartSpace = new ChartSpace(); chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") }); DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild <DocumentFormat.OpenXml.Drawing.Charts.Chart>( new DocumentFormat.OpenXml.Drawing.Charts.Chart()); // Create a new clustered column chart. PlotArea plotArea = chart.AppendChild <PlotArea>(new PlotArea()); Layout layout = plotArea.AppendChild <Layout>(new Layout()); BarChart barChart = plotArea.AppendChild <BarChart>(new BarChart(new BarDirection() { Val = new EnumValue <BarDirectionValues>(BarDirectionValues.Column) }, new BarGrouping() { Val = new EnumValue <BarGroupingValues>(BarGroupingValues.Clustered) })); uint i = 0; // Iterate through each key in the Dictionary collection and add the key to the chart Series // and add the corresponding value to the chart Values. foreach (string key in data.Keys) { BarChartSeries barChartSeries = barChart.AppendChild <BarChartSeries>(new BarChartSeries(new Index() { Val = new UInt32Value(i) }, new Order() { Val = new UInt32Value(i) }, new SeriesText(new NumericValue() { Text = key }))); StringLiteral strLit = barChartSeries.AppendChild <CategoryAxisData>(new CategoryAxisData()).AppendChild <StringLiteral>(new StringLiteral()); strLit.Append(new PointCount() { Val = new UInt32Value(1U) }); strLit.AppendChild <StringPoint>(new StringPoint() { Index = new UInt32Value(0U) }).Append(new NumericValue(key)); NumberLiteral numLit = barChartSeries.AppendChild <DocumentFormat.OpenXml.Drawing.Charts.Values>( new DocumentFormat.OpenXml.Drawing.Charts.Values()).AppendChild <NumberLiteral>(new NumberLiteral()); numLit.Append(new FormatCode("General")); numLit.Append(new PointCount() { Val = new UInt32Value(1U) }); numLit.AppendChild <NumericPoint>(new NumericPoint() { Index = new UInt32Value(0u) }) .Append(new NumericValue(data[key].ToString())); i++; } barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) }); barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) }); //// Add the Category Axis. CategoryAxis catAx = plotArea.AppendChild <CategoryAxis>(new CategoryAxis(new AxisId() { Val = new UInt32Value(48650112u) }, new Scaling(new Orientation() { Val = new EnumValue <DocumentFormat. OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) }), new AxisPosition() { Val = new EnumValue <AxisPositionValues>(AxisPositionValues.Bottom) }, new TickLabelPosition() { Val = new EnumValue <TickLabelPositionValues>(TickLabelPositionValues.NextTo) }, new CrossingAxis() { Val = new UInt32Value(48672768U) }, new Crosses() { Val = new EnumValue <CrossesValues>(CrossesValues.AutoZero) }, new AutoLabeled() { Val = new BooleanValue(true) }, new LabelAlignment() { Val = new EnumValue <LabelAlignmentValues>(LabelAlignmentValues.Center) }, new LabelOffset() { Val = new UInt16Value((ushort)100) })); // Add the Value Axis. ValueAxis valAx = plotArea.AppendChild <ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) }, new Scaling(new Orientation() { Val = new EnumValue <DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>( DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) }), new AxisPosition() { Val = new EnumValue <AxisPositionValues>(AxisPositionValues.Left) }, new MajorGridlines(), new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat() { FormatCode = new StringValue("General"), SourceLinked = new BooleanValue(true) }, new TickLabelPosition() { Val = new EnumValue <TickLabelPositionValues> (TickLabelPositionValues.NextTo) }, new CrossingAxis() { Val = new UInt32Value(48650112U) }, new Crosses() { Val = new EnumValue <CrossesValues>(CrossesValues.AutoZero) }, new CrossBetween() { Val = new EnumValue <CrossBetweenValues>(CrossBetweenValues.Between) })); // Add the chart Legend. Legend legend = chart.AppendChild <Legend>(new Legend(new LegendPosition() { Val = new EnumValue <LegendPositionValues>(LegendPositionValues.Right) }, new Layout())); chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) }); // Save the chart part. chartPart.ChartSpace.Save(); // Position the chart on the worksheet using a TwoCellAnchor object. drawingsPart.WorksheetDrawing = new WorksheetDrawing(); TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild <TwoCellAnchor>(new TwoCellAnchor()); twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("1"), new ColumnOffset("581025"), new RowId("1"), new RowOffset("114300"))); twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("10"), new ColumnOffset("276225"), new RowId("16"), new RowOffset("0"))); // Append a GraphicFrame to the TwoCellAnchor object. DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame = twoCellAnchor.AppendChild <DocumentFormat.OpenXml. Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing. Spreadsheet.GraphicFrame()); graphicFrame.Macro = ""; graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties( new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" }, new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties())); graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L }, new Extents() { Cx = 0L, Cy = 0L })); graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) }) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" })); twoCellAnchor.Append(new ClientData()); // Save the WorksheetDrawing object. drawingsPart.WorksheetDrawing.Save(); } }
private bool UpdateScales() { var valueScale = ValueScale; var categoryScale = CategoryScale; CategoryScale = new LinearScale { Output = CategoryScale.Output }; ValueScale = new LinearScale { Output = ValueScale.Output }; var visibleSeries = Series.Where(series => series.Visible).ToList(); var invisibleSeries = Series.Where(series => series.Visible == false).ToList(); if (!visibleSeries.Any() && invisibleSeries.Any()) { visibleSeries.Add(invisibleSeries.Last()); } foreach (var series in visibleSeries) { CategoryScale = series.TransformCategoryScale(CategoryScale); ValueScale = series.TransformValueScale(ValueScale); } AxisBase xAxis = CategoryAxis; AxisBase yAxis = ValueAxis; if (ShouldInvertAxes()) { xAxis = ValueAxis; yAxis = CategoryAxis; } else { CategoryScale.Padding = CategoryAxis.Padding; } CategoryScale.Resize(xAxis.Min, xAxis.Max); if (xAxis.Step != null) { CategoryScale.Step = xAxis.Step; CategoryScale.Round = false; } ValueScale.Resize(yAxis.Min, yAxis.Max); if (yAxis.Step != null) { ValueScale.Step = yAxis.Step; ValueScale.Round = false; } var legendSize = Legend.Measure(this); var valueAxisSize = ValueAxis.Measure(this); var categoryAxisSize = CategoryAxis.Measure(this); if (!ShouldRenderAxes()) { valueAxisSize = categoryAxisSize = 0; } MarginTop = MarginRight = 32; MarginLeft = valueAxisSize; MarginBottom = Math.Max(32, categoryAxisSize); if (Legend.Visible) { if (Legend.Position == LegendPosition.Right || Legend.Position == LegendPosition.Left) { if (Legend.Position == LegendPosition.Right) { MarginRight = legendSize + 16; } else { MarginLeft = legendSize + 16 + valueAxisSize; } } else if (Legend.Position == LegendPosition.Top || Legend.Position == LegendPosition.Bottom) { if (Legend.Position == LegendPosition.Top) { MarginTop = legendSize + 16; } else { MarginBottom = legendSize + 16 + categoryAxisSize; } } } CategoryScale.Output = new ScaleRange { Start = MarginLeft, End = Width.Value - MarginRight }; ValueScale.Output = new ScaleRange { Start = Height.Value - MarginBottom, End = MarginTop }; ValueScale.Fit(ValueAxis.TickDistance); CategoryScale.Fit(CategoryAxis.TickDistance); var stateHasChanged = false; if (!ValueScale.IsEqualTo(valueScale)) { stateHasChanged = true; } if (!CategoryScale.IsEqualTo(categoryScale)) { stateHasChanged = true; } return(stateHasChanged); }
public static void Export(string filePath, double[] data) { SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY"); ExcelFile excel = new ExcelFile(); //Excel默认字体 excel.DefaultFontName = TIMESNEWROMAN; //Excel文档属性设置 excel.DocumentProperties.BuiltIn.Add(new KeyValuePair <BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Title, TITLE)); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair <BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Author, "CNXY")); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair <BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Company, "CNXY")); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair <BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Comments, "By CNXY.Website: http://www.cnc6.cn")); //新建一个Sheet表格 ExcelWorksheet sheet = excel.Worksheets.Add(TITLE); //设置表格保护 sheet.ProtectionSettings.SetPassword("cnxy"); sheet.Protected = true; //设置网格线不可见 sheet.ViewOptions.ShowGridLines = false; //定义一个B2-G3的单元格范围 CellRange range = sheet.Cells.GetSubrange("B2", "J3"); range.Value = "Chart"; range.Merged = true; //定义一个单元格样式 CellStyle style = new CellStyle(); //设置边框 style.Borders.SetBorders(MultipleBorders.Outside, SpreadsheetColor.FromName(ColorName.Red), LineStyle.Thin); //设置水平对齐模式 style.HorizontalAlignment = HorizontalAlignmentStyle.Center; //设置垂直对齐模式 style.VerticalAlignment = VerticalAlignmentStyle.Center; //设置字体 style.Font.Size = 22 * PT; style.Font.Weight = ExcelFont.BoldWeight; style.Font.Color = SpreadsheetColor.FromName(ColorName.Red); range.Style = style; //增加Chart LineChart chart = (LineChart)sheet.Charts.Add(ChartType.Line, "B4", "J22"); chart.Title.IsVisible = false; chart.Axes.Horizontal.Title.Text = "Time"; chart.Axes.Vertical.Title.Text = "Voltage"; ValueAxis axisY = chart.Axes.VerticalValue; //Y轴最大刻度与最小刻度 axisY.Minimum = -100; axisY.Maximum = 100; //Y轴主要与次要单位大小 axisY.MajorUnit = 20; axisY.MinorUnit = 10; //Y轴主要与次要网格是否可见 axisY.MajorGridlines.IsVisible = true; axisY.MinorGridlines.IsVisible = true; //Y轴刻度线类型 axisY.MajorTickMarkType = TickMarkType.Cross; axisY.MinorTickMarkType = TickMarkType.Inside; Random random = new Random(); data = new double[LENGTH]; for (int i = 0; i < LENGTH; i++) { if (random.Next(0, 100) > 50) { data[i] = random.NextDouble() * 100; } else { data[i] = -random.NextDouble() * 100; } } chart.Series.Add("Random", data); //尾部信息 range = sheet.Cells.GetSubrange("B23", "J24"); range.Value = $"Write Time:{DateTime.Now:yyyy-MM-dd HH:mm:ss} By CNXY"; range.Merged = true; //B25(三种单元格模式) sheet.Cells["B25"].Value = "http://www.cnc6.cn"; sheet.Cells[24, 1].Style.FillPattern.PatternStyle = FillPatternStyle.Solid; sheet.Rows[24].Cells[1].Style.FillPattern.PatternForegroundColor = SpreadsheetColor.FromName(ColorName.Red); //B25,J25 sheet.Cells.GetSubrangeAbsolute(24, 1, 24, 9).Merged = true; try { excel.Save(filePath); Process.Start(filePath); MessageBox.Show("Write successfully"); } catch (Exception ex) { MessageBox.Show(ex.Message); } MessageBox.Show("Press any key to continue."); }
private void drawGrid() { if (!gdef.onlyGraph) { Pen shade1 = new Pen(gdef.colors[RrdGraphConstants.COLOR_SHADEA], 1); Pen shade2 = new Pen(gdef.colors[RrdGraphConstants.COLOR_SHADEB],1); worker.drawLine(0, 0, im.xgif - 1, 0, shade1); worker.drawLine(1, 1, im.xgif - 2, 1, shade1); worker.drawLine(0, 0, 0, im.ygif - 1, shade1); worker.drawLine(1, 1, 1, im.ygif - 2, shade1); worker.drawLine(im.xgif - 1, 0, im.xgif - 1, im.ygif - 1, shade2); worker.drawLine(0, im.ygif - 1, im.xgif - 1, im.ygif - 1, shade2); worker.drawLine(im.xgif - 2, 1, im.xgif - 2, im.ygif - 2, shade2); worker.drawLine(1, im.ygif - 2, im.xgif - 2, im.ygif - 2, shade2); if (gdef.drawXGrid) { new TimeAxis(this).draw(); } if (gdef.drawYGrid) { bool ok; if (gdef.altYMrtg) { ok = new ValueAxisMrtg(this).draw(); } else if (gdef.logarithmic) { ok = new ValueAxisLogarithmic(this).draw(); } else { ok = new ValueAxis(this).draw(); } if (!ok) { String msg = "No Data Found"; worker.drawString(msg, im.xgif / 2 - (int) worker.getStringWidth(msg, gdef.largeFont) / 2, (2 * im.yorigin - im.ysize) / 2, gdef.largeFont,new SolidBrush(gdef.colors[RrdGraphConstants.COLOR_FONT])); } } } }
/// <summary> /// refer: https://www.cnblogs.com/kulong995/p/5237796.html /// </summary> /// <returns></returns> public static string TemperatureBar() { ChartOption option = new ChartOption(); option.Title().Text("温度计式图表").Subtext("Form ExcelHome"). Sublink("http://e.weibo.com/1341556070/AizJXrAEa"); option.ToolTip().Trigger(TriggerType.axis) // 原作者嘅 code,好似有 bug,暫時取消 //.Formatter(new JRaw(@"function (params){ // return params[0].name + '<br/>' // + params[0].seriesName + ' : ' + params[0].value + '<br/>' // + params[1].seriesName + ' : ' + (params[1].value + params[0].value); // }")) .AxisPointer().Type(AxisPointType.shadow); option.Legend().Data("Acutal", "Forecast"); Feature feature = new Feature(); feature.Mark().Show(true); feature.DataView().Show(true).ReadOnly(false); feature.Restore().Show(true); feature.SaveAsImage().Show(true); option.ToolBox().Show(true).SetFeature(feature); option.Grid().Y(80).Y2(30); CategoryAxis x = new CategoryAxis(); x.Data("Cosco", "CMA", "APL", "OOCL", "Wanhai", "Zim"); option.XAxis(x); ValueAxis y = new ValueAxis(); y.BoundaryGap(new List <double>() { 0, 0.1 }); option.YAxis(y); var tomatoStyle = new ItemStyle(); tomatoStyle.Normal().Color("tomato").BarBorderRadius(0) .BarBorderColor("tomato").BarBorderWidth(6) .Label().Show(true).Position(StyleLabelType.insideTop); Bar b1 = new Bar("Acutal"); b1.Stack("sum"); b1.SetItemStyle(tomatoStyle); b1.Data(260, 200, 220, 120, 100, 80); var forecastStyle = new ItemStyle(); var pattern = @"(""(?:[^""\\]|\\.)*"")|\s+"; // remove space and CRLF var raw = @"function (params) {for (var i = 0, l = option.xAxis[0].data.length; i < l; i++) {if (option.xAxis[0].data[i] == params.name) {return option.series[0].data[i] + params.value;}}}"; var formatter = string.Format(@"eval(""{0}"")", raw); var tmp = new JRaw(raw); //! HACK: Formatter 去到 EChartsBox.html script 會出 JSON.parse error forecastStyle.Normal().Color("#fff").BarBorderRadius(0) .BarBorderColor("tomato").BarBorderWidth(6) .Label().Show(true).Position(StyleLabelType.top) .Formatter(new JRaw(@"function (params) { for (var i = 0, l = option.xAxis[0].data.length; i < l; i++) { if (option.xAxis[0].data[i] == params.name) { return option.series[0].data[i] + params.value; } } }")) //.Formatter(new JRaw(formatter)) .TextStyle().Color("tomato"); Bar b2 = new Bar("Forecast"); b2.Stack("sum"); b2.SetItemStyle(forecastStyle); b2.Data(40, 80, 50, 80, 80, 70); option.Series(b1, b2); var result = JsonHelper.ObjectToJson2(option); return(result); }
/// <summary> /// draw the 2D bar chart /// index start from 1 /// </summary> /// <param name="startx">index start from 1 for row</param> /// <param name="starty">index start from 1 for column</param> /// <param name="columnCount"></param> /// <param name="rowCount"></param> public void InsertChartInSpreadsheet(WorksheetPart sheetpart, string sheetName, int startx, int starty, int columnCount, int rowCount, int chart_pointx, int chart_pointy) { WorksheetPart worksheetPart = CurrentWorksheetPart; #region SDK How to example code // Add a new drawing to the worksheet. DrawingsPart drawingsPart = worksheetPart.AddNewPart <DrawingsPart>(); worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing() { Id = worksheetPart.GetIdOfPart(drawingsPart) }); worksheetPart.Worksheet.Save(); // Add a new chart and set the chart language to English-US. ChartPart chartPart = drawingsPart.AddNewPart <ChartPart>(); chartPart.ChartSpace = new ChartSpace(); chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") }); DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild <DocumentFormat.OpenXml.Drawing.Charts.Chart>( new DocumentFormat.OpenXml.Drawing.Charts.Chart()); // Create a new clustered column chart. PlotArea plotArea = chart.AppendChild <PlotArea>(new PlotArea()); Layout layout = plotArea.AppendChild <Layout>(new Layout()); BarChart barChart = plotArea.AppendChild <BarChart>(new BarChart(new BarDirection() { Val = new EnumValue <BarDirectionValues>(BarDirectionValues.Column) }, new BarGrouping() { Val = new EnumValue <BarGroupingValues>(BarGroupingValues.Clustered) })); #endregion string sheetName = GetCurrentSheetName(); string columnName = GetColumnName(starty - 1); string formulaString = string.Format("{0}!${1}${2}:${3}${4}", sheetName, columnName, startx + 1, columnName, startx + rowCount - 1); CategoryAxisData cad = new CategoryAxisData(); cad.StringReference = new StringReference() { Formula = new DocumentFormat.OpenXml.Drawing.Charts.Formula(formulaString) }; uint i = 0; for (int sIndex = 1; sIndex < columnCount; sIndex++) { columnName = GetColumnName(starty + sIndex - 1); formulaString = string.Format("{0}!${1}${2}", sheetName, columnName, startx); SeriesText st = new SeriesText(); st.StringReference = new StringReference() { Formula = new DocumentFormat.OpenXml.Drawing.Charts.Formula(formulaString) }; formulaString = string.Format("{0}!${1}${2}:${3}${4}", sheetName, columnName, startx + 1, columnName, startx + rowCount - 1); DocumentFormat.OpenXml.Drawing.Charts.Values v = new DocumentFormat.OpenXml.Drawing.Charts.Values(); v.NumberReference = new NumberReference() { Formula = new DocumentFormat.OpenXml.Drawing.Charts.Formula(formulaString) }; BarChartSeries barChartSeries = barChart.AppendChild <BarChartSeries>(new BarChartSeries(new Index() { Val = new UInt32Value(i) }, new Order() { Val = new UInt32Value(i) }, st, v)); if (sIndex == 1) { barChartSeries.AppendChild(cad); } i++; } #region SDK how to example Code barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) }); barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) }); // Add the Category Axis. CategoryAxis catAx = plotArea.AppendChild <CategoryAxis>(new CategoryAxis(new AxisId() { Val = new UInt32Value(48650112u) }, new Scaling(new Orientation() { Val = new EnumValue <DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>( DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) }), new AxisPosition() { Val = new EnumValue <AxisPositionValues>(AxisPositionValues.Bottom) }, new TickLabelPosition() { Val = new EnumValue <TickLabelPositionValues>(TickLabelPositionValues.NextTo) }, new CrossingAxis() { Val = new UInt32Value(48672768U) }, new Crosses() { Val = new EnumValue <CrossesValues>(CrossesValues.AutoZero) }, new AutoLabeled() { Val = new BooleanValue(true) }, new LabelAlignment() { Val = new EnumValue <LabelAlignmentValues>(LabelAlignmentValues.Center) }, new LabelOffset() { Val = new UInt16Value((ushort)100) })); // Add the Value Axis. ValueAxis valAx = plotArea.AppendChild <ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) }, new Scaling(new Orientation() { Val = new EnumValue <DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>( DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) }), new AxisPosition() { Val = new EnumValue <AxisPositionValues>(AxisPositionValues.Left) }, new MajorGridlines(), new DocumentFormat.OpenXml.Drawing.Charts.NumberFormat() { FormatCode = new StringValue("General"), SourceLinked = new BooleanValue(true) }, new TickLabelPosition() { Val = new EnumValue <TickLabelPositionValues>(TickLabelPositionValues.NextTo) }, new CrossingAxis() { Val = new UInt32Value(48650112U) }, new Crosses() { Val = new EnumValue <CrossesValues>(CrossesValues.AutoZero) }, new CrossBetween() { Val = new EnumValue <CrossBetweenValues>(CrossBetweenValues.Between) })); // Add the chart Legend. Legend legend = chart.AppendChild <Legend>(new Legend(new LegendPosition() { Val = new EnumValue <LegendPositionValues>(LegendPositionValues.Right) }, new Layout())); chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) }); // Save the chart part. chartPart.ChartSpace.Save(); // Position the chart on the worksheet using a TwoCellAnchor object. drawingsPart.WorksheetDrawing = new WorksheetDrawing(); TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild <TwoCellAnchor>(new TwoCellAnchor()); twoCellAnchor.Append(new FromMarker(new ColumnId("9"), new ColumnOffset("581025"), new RowId("17"), new RowOffset("114300"))); twoCellAnchor.Append(new ToMarker(new ColumnId("17"), new ColumnOffset("276225"), new RowId("32"), new RowOffset("0"))); // Append a GraphicFrame to the TwoCellAnchor object. DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame = twoCellAnchor.AppendChild <DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame>( new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame()); graphicFrame.Macro = ""; graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties( new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" }, new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties())); graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L }, new Extents() { Cx = 0L, Cy = 0L })); graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) }) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" })); twoCellAnchor.Append(new ClientData()); // Save the WorksheetDrawing object. drawingsPart.WorksheetDrawing.Save(); #endregion }
private void Start() { this.reelValueAxis = this.gameObject.GetComponent <ValueAxis>(); this.reelAxisValueRigidbody = this.gameObject.GetComponent <Rigidbody>(); }