This is the code which i used to generate pie chart . I need to add percentage value to piechart series.Tries few ways but did not find solution.I have attached my working code output image and expected image .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Xml;
using System.Collections;
public bool GetPieChart(string XML , string Path)
{
try
{
// create chart instance
var chart = new Chart();
// set chart height and width
chart.Height = 500;
chart.Width = 600;
// Add legend to chart
chart.Legends.Add(new Legend() { Name = "Legend" });
chart.Legends[0].Font = new Font("Verdana", 10);
chart.Legends[0].Docking = Docking.Bottom;
ArrayList xAxisData = new ArrayList();
ArrayList yAxisData = new ArrayList();
XmlDocument xml = new XmlDocument();
xml.LoadXml(XML);
XmlNodeList multiLine = xml.DocumentElement.SelectNodes("/Report/PieChart/series");
// Set Chart Title
string title = xml.SelectSingleNode("/Report").Attributes["Name"].Value.ToString();
chart.Titles.Add(title);
chart.Titles[0].Font = new Font("Verdana", 12);
// Set chart properties
var chartArea = new ChartArea();
chart.ChartAreas.Add(chartArea);
Series series;
// Add data to the chart
foreach (XmlNode seriesNode in multiLine)
{
xAxisData.Clear();
yAxisData.Clear();
series = new Series();
string seriesName = seriesNode.Attributes["name"].Value.ToString();
XmlNodeList detailsList = seriesNode.SelectNodes("datapoint");
foreach (XmlNode detailNode in detailsList)
{
xAxisData.Add(detailNode.Attributes["Label"].Value.ToString());
int value;
string st = detailNode.Attributes["value"].Value.ToString();
int.TryParse(st, out value);
yAxisData.Add(value);
}
// set series properties
series.Name = seriesName;
series.ChartType = SeriesChartType.Pie;
chart.Series.Add(series);
chart.Series[seriesName].Points.DataBindXY(xAxisData, yAxisData);
chart.Series[seriesName]["PieLabelStyle"] = "Outside";
chart.Series[seriesName]["PieLineColor"] = "Black";
}
chart.SaveImage(Path, ChartImageFormat.Jpeg);
}
catch (Exception ex)
{
}
return true;
}
This is the out put from this code
This is what i expect
Guys need your help to do that ?
foreach (DataPoint p in YourChart.Series["YourSeriesName"].Points)
{
p.Label = "#PERCENT\n#VALX";
}
Finally found solution. Now works well.
chart.Series[seriesName].XValueMember = "Name";
chart.Series[seriesName].YValueMembers = "Count";
chart.Series[seriesName].IsValueShownAsLabel = true;
escape percentage sign with double percentage char. look for the sample below
Chart1.Series.Add(series);
Series series1 = Chart1.Series[0];
series1.Points.DataBindXY(xValues, yValues);
Title ti = new Title()
ti.TextStyle = TextStyle.Emboss;
ti.Text = ((yValues[0] / 100) * 100) + #"%%";//double Percentage sign
ti.Font = new Font("Times New Roman", 40, FontStyle.Bold);
ti.Position.X = 50;
ti.Position.Y = 50;
Chart1.Titles.Add(ti);
this maybe help. This code is for a Pie Chart with percentage inside the Pie and labels(strings) in the legends: Where datosSeries = List
string[] labels = datosSeries.Select(o => o.Week).ToArray();
float[] data = datosSeries.Select(o => o.ProfitSerie).ToArray();
chart2.Series.Add("Series1");
chart2.Series[0].Points.DataBindXY(labels, data);
chart2.Series[0].ChartType = SeriesChartType.Pie;
chart2.Series[0]["PieLabelStyle"] = "Outside";
chart2.Series[0].BorderWidth = 1;
chart2.Series[0].BorderColor = System.Drawing.Color.FromArgb(26, 59, 105);
chart2.Series[0].Label = "#PERCENT{P2}";
chart2.Legends.Add(new Legend("Default"));
// Add Color column
LegendCellColumn firstColumn = new LegendCellColumn();
firstColumn.ColumnType = LegendCellColumnType.SeriesSymbol;
firstColumn.HeaderText = "";
chart2.Legends["Default"].CellColumns.Add(firstColumn);
// Add name cell column
LegendCellColumn percentColumn = new LegendCellColumn();
percentColumn.Text = "#VALX";
percentColumn.HeaderText = "Tipo de Gastos";
percentColumn.Name = "nameColumn";
chart2.Legends["Default"].CellColumns.Add(percentColumn);
//Format the legend
chart2.Legends["Default"].LegendStyle = LegendStyle.Table;
chart2.Legends["Default"].TableStyle = LegendTableStyle.Tall;
chart2.Legends["Default"].DockedToChartArea = "ChartArea1";
chart2.Legends["Default"].IsDockedInsideChartArea = false;
chart2.Legends["Default"].Docking = Docking.Bottom;
Related
I'm making a journal application for myself in c# where i can make journals with dates attached to it.
I'm using a foreach statement to let the data display in the textboxes. I can't figure out how to display the journals in order (old->new) with the dates in Textbox3 (t3). I live in Europe so It's DD/MM/YYYY. I hope it's clear, thanks.
string[] journalfolder = Directory.GetDirectories(#"D:\panel\Journal\", "*");
foreach (string file in journalfolder)
{
Color grey = new Color();
TextBox t1 = new TextBox();
t1.Name = "t1_" + (t1.Controls.Count + 1);
t1.Location = new Point(265, 20);
grey = Color.FromArgb(31, 31, 31);
t1.Width = 332;
t1.BackColor = grey;
t1.BorderStyle = BorderStyle.None;
t1.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\text.txt");
t1.Text = lines[0];
}
catch { }
TextBox t2 = new TextBox();
t2.Name = "t2_" + (t2.Controls.Count + 1);
t2.Location = new Point(265, 39);
t2.Width = 332;
t2.Height = 155;
grey = Color.FromArgb(31,31,31);
t2.BackColor = grey;
t2.Multiline = true;
t2.BorderStyle = BorderStyle.None;
t2.ForeColor = Color.White;
try
{
using (var sr = new StreamReader(file + #"\text.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
t2.Text = line;
}
}
}
catch { }
TextBox t3 = new TextBox();
t3.Name = "t3_" + (t3.Controls.Count + 1);
t3.Location = new Point(265, 199);
grey = Color.FromArgb(31, 31, 31);
t3.Width = 332;
t3.BackColor = grey;
t3.BorderStyle = BorderStyle.None;
t3.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\date.txt");
t3.Text = lines[0];
}
catch { }
Panel image = new Panel();
image.Name = "image" + (image.Controls.Count + 1);
image.Location = new Point(20, 20);
image.BackgroundImageLayout = ImageLayout.Zoom;
image.Width = 223;
image.Width = 192;
try
{
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.ico,*.eps,*.tif,*.tiff";
foreach (string imageFile in Directory.GetFiles(file + #"\Files", "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Console.WriteLine(imageFile);
image.BackgroundImage = Image.FromFile(imageFile);
}
}
catch { }
Panel p = new Panel();
p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
p.BackColor = Color.FromArgb(49,49,49);
p.Width = 628;
p.Height = 236;
p.Controls.Add(t1);
p.Controls.Add(t2);
p.Controls.Add(t3);
p.Controls.Add(image);
flowLayoutPanel1.Controls.Add(p);
}
I'm not quite sure I understand your requirement correctly, but I'll give it a try ...
The date is managed in a date.txt file. It contains the date in the format DD/MM/YYYY, correct?
DateTime timestamp = DateTime.Parse("ValueFromFile");
It is best to put the title, text and date in a class or struct. Maybe something like this:
public class Data
{
public string Title { get; set; }
public string Text { get; set; }
public DateTime Timestamp { get; set; }
}
You should put all the elements you have read into a list or a dictionary before displaying them on the UI and processing them further. Once all the data is in this list, you can easily sort it by date using LINQ.
List<Data> values = new List<Data>();
// TODO
// Add the items
foreach (Data item in values.OrderBy((item) => item.Timestamp))
{
}
// Or
foreach (Data item in values.OrderByDescending((item) => item.Timestamp))
{
}
I have written a method to insert a table in a word document using Open XML. The method accepts a generic list and a few parameters to control number of columns, column headings etc.
That all works fine.
However when populating the cells in the table I want to pull out the values for each row and place them in their corresponding columns. Given the names of the properties are going to change depending on the contents of the generic list, I am not sure how to accomplish this.
Anyone that can point me in the right direction it would be appreciated.
void InsertTable<T>(List<T> tableData, int[] tableHeadingCount, string[] columnHeadings, string locationInDocument)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(_newDocument, true))
{
var docPart = myDoc.MainDocumentPart;
var doc = docPart.Document;
var table = new Table();
var tableBorderTop = new TopBorder();
var tableBorderBottom = new BottomBorder();
var tableBorderLeft = new LeftBorder();
var tableBorderRight = new RightBorder();
var tableBorderHorizontal = new InsideHorizontalBorder();
var tableBorderVertical = new InsideVerticalBorder();
var tableProperties = new TableProperties();
var borders = new TableBorders();
// Set Border Styles for Table
tableBorderTop.Val = BorderValues.Single;
tableBorderTop.Size = 6;
tableBorderBottom.Val = BorderValues.Single;
tableBorderBottom.Size = 6;
tableBorderLeft.Val = BorderValues.Single;
tableBorderLeft.Size = 6;
tableBorderRight.Val = BorderValues.Single;
tableBorderRight.Size = 6;
tableBorderHorizontal.Val = BorderValues.Single;
tableBorderHorizontal.Size = 6;
tableBorderVertical.Val = BorderValues.Single;
tableBorderVertical.Size = 6;
// Assign Border Styles to Table Borders
borders.TopBorder = tableBorderTop;
borders.BottomBorder = tableBorderBottom;
borders.LeftBorder = tableBorderLeft;
borders.RightBorder = tableBorderRight;
borders.InsideHorizontalBorder = tableBorderHorizontal;
borders.InsideVerticalBorder = tableBorderVertical;
// Append Border Styles to Table Properties
tableProperties.Append(borders);
// Assign Table Properties to Table
table.Append(tableProperties);
var tableRowHeader = new TableRow();
tableRowHeader.Append(new TableRowHeight() { Val = 2000 });
for (int i = 0; i < tableHeadingCount.Length; i++)
{
var tableCellHeader = new TableCell();
//Assign Font Properties to Run
var runPropHeader = new RunProperties();
runPropHeader.Append(new Bold());
runPropHeader.Append(new Color() { Val = "000000" });
//Create New Run
var runHeader = new Run();
//Assign Font Properties to Run
runHeader.Append(runPropHeader);
var columnHeader = new Text();
//Assign the Pay Rule Name to the Run
columnHeader = new Text(columnHeadings[i]);
runHeader.Append(columnHeader);
//Create Properties for Paragraph
var justificationHeader = new Justification();
justificationHeader.Val = JustificationValues.Left;
var paraPropsHeader = new ParagraphProperties(justificationHeader);
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
paraPropsHeader.Append(spacing);
var paragraphHeader = new Paragraph();
paragraphHeader.Append(paraPropsHeader);
paragraphHeader.Append(runHeader);
tableCellHeader.Append(paragraphHeader);
var tableCellPropertiesHeader = new TableCellProperties();
var tableCellWidthHeader = new TableCellWidth();
tableCellPropertiesHeader.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "#C0C0C0" });
var textDirectionHeader = new TextDirection();
textDirectionHeader.Val = TextDirectionValues.BottomToTopLeftToRight;
tableCellPropertiesHeader.Append(textDirectionHeader);
tableCellWidthHeader.Type = TableWidthUnitValues.Dxa;
tableCellWidthHeader.Width = "2000";
tableCellPropertiesHeader.Append(tableCellWidthHeader);
tableCellHeader.Append(tableCellPropertiesHeader);
tableRowHeader.Append(tableCellHeader);
}
tableRowHeader.AppendChild(new TableHeader());
table.Append(tableRowHeader);
//Create New Row in Table for Each Record
foreach (var record in tableData)
{
var tableRow = new TableRow();
for (int i = 0; i < tableHeadingCount.Length; i++)
{
//**** This is where I dynamically want to iterate through selected properties and output the value ****
var propertyText = "Test";
var tableCell = new TableCell();
//Assign Font Properties to Run
var runProp = new RunProperties();
runProp.Append(new Bold());
runProp.Append(new Color() { Val = "000000" });
//Create New Run
var run = new Run();
//Assign Font Properties to Run
run.Append(runProp);
//Assign the text to the Run
var text = new Text(propertyText);
run.Append(text);
//Create Properties for Paragraph
var justification = new Justification();
justification.Val = JustificationValues.Left;
var paraProps = new ParagraphProperties(justification);
var paragraph = new Paragraph();
paragraph.Append(paraProps);
paragraph.Append(run);
tableCell.Append(paragraph);
var tableCellProperties = new TableCellProperties();
var tableCellWidth = new TableCellWidth();
tableCellWidth.Type = TableWidthUnitValues.Dxa;
tableCellWidth.Width = "2000";
tableCellProperties.Append(tableCellWidth);
tableCell.Append(tableCellProperties);
tableRow.Append(tableCell);
}
table.Append(tableRow);
}
var res = from bm in docPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == locationInDocument
select bm;
var bookmark = res.SingleOrDefault();
var parent = bookmark.Parent; // bookmark's parent element
Paragraph newParagraph = new Paragraph();
parent.InsertAfterSelf(newParagraph);
if (bookmark != null)
{
newParagraph.InsertBeforeSelf(table);
}
}
}
I resolved this issue by tackling the problem another way. Essentially rather than passing a List to the Insert Table Method. I decided to Pass a Multi-Dimensional Array with all the data need for the table including the table headings. This essentially meant that the Insert Table method would be more generic and any customization i.e. Generating Data, Specifying Column Headings etc would be done in the Method calling Insert Table.
Does anyone know how to do this?
I'm using EPPlus in .Net and have created a pivot table with 2 row fields and one summary datafield:
Dim Pivot As OfficeOpenXml.Table.PivotTable.ExcelPivotTable
Pivot = wksPivot.PivotTables.Add(wksPivot.Cells("A1"), Datarange, "pName")
Pivot.RowFields.Add(Pivot.Fields("Fld1")).Sort = Table.PivotTable.eSortType.Ascending
Pivot.RowFields.Add(Pivot.Fields("Fld2")).Sort = Table.PivotTable.eSortType.Ascending
Dim dtaFld As OfficeOpenXml.Table.PivotTable.ExcelPivotTableDataField
dtaFld = Pivot.DataFields.Add(Pivot.Fields("XYZ"))
dtaFld.Function = Table.PivotTable.DataFieldFunctions.Sum
Everything works great, but I want to have the Pivot Table start off as collapsed when the user opens the workbook (In excel, when you're creating the pivot table, you can right-click in the data element and select "Expand / Collapse" > "Collapse Entire Field"
Hot can I do this via code?? (And I'm willing to use direct OpenXML if EPPlus doesn't support this yet...)
ALSO, is there a way to delete out the Raw data from the workbook so that the pivot table still works? i've tried and when I open the workbook, my pivot table is blank? - My current logic has led me to this question... Any thoughts??
(I do know I wrote this question in VB. but I added both the C# & VB tags to this question - I'm comfortable with code in either language - Thanks!!)
Could make it xlsm and add vba to it. This is probably the worst answer to this solution but it achives full collapse. I have provided a working example, just copy past into a new console app. add the epplus dependency, "F5".
modified/taken from http://epplus.codeplex.com/SourceControl/latest#SampleApp/Sample15.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeOpenXml.Table;
using OfficeOpenXml.Table.PivotTable;
using OfficeOpenXml;
using System.IO;
namespace pTable
{
class Program
{
static void Main(string[] args)
{
//ExcelPackage _pck = new ExcelPackage();
Directory.CreateDirectory(string.Format("Test"));
//ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsx"));
ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsm"));
var wsPivot1 = _pck.Workbook.Worksheets.Add("Rows-Data on columns");
var ws = _pck.Workbook.Worksheets.Add("Data");
ws.Cells["K1"].Value = "Item";
ws.Cells["L1"].Value = "Category";
ws.Cells["M1"].Value = "Stock";
ws.Cells["N1"].Value = "Price";
ws.Cells["O1"].Value = "Date for grouping";
ws.Cells["K2"].Value = "Crowbar";
ws.Cells["L2"].Value = "Hardware";
ws.Cells["M2"].Value = 12;
ws.Cells["N2"].Value = 85.2;
ws.Cells["O2"].Value = new DateTime(2010, 1, 31);
ws.Cells["K3"].Value = "Crowbar";
ws.Cells["L3"].Value = "Hardware";
ws.Cells["M3"].Value = 15;
ws.Cells["N3"].Value = 12.2;
ws.Cells["O3"].Value = new DateTime(2010, 2, 28);
ws.Cells["K4"].Value = "Hammer";
ws.Cells["L4"].Value = "Hardware";
ws.Cells["M4"].Value = 550;
ws.Cells["N4"].Value = 72.7;
ws.Cells["O4"].Value = new DateTime(2010, 3, 31);
ws.Cells["K5"].Value = "Hammer";
ws.Cells["L5"].Value = "Hardware";
ws.Cells["M5"].Value = 120;
ws.Cells["N5"].Value = 11.3;
ws.Cells["O5"].Value = new DateTime(2010, 4, 30);
ws.Cells["K6"].Value = "Crowbar";
ws.Cells["L6"].Value = "Hardware";
ws.Cells["M6"].Value = 120;
ws.Cells["N6"].Value = 173.2;
ws.Cells["O6"].Value = new DateTime(2010, 5, 31);
ws.Cells["K7"].Value = "Hammer";
ws.Cells["L7"].Value = "Hardware";
ws.Cells["M7"].Value = 1;
ws.Cells["N7"].Value = 4.2;
ws.Cells["O7"].Value = new DateTime(2010, 6, 30);
ws.Cells["K8"].Value = "Saw";
ws.Cells["L8"].Value = "Hardware";
ws.Cells["M8"].Value = 4;
ws.Cells["N8"].Value = 33.12;
ws.Cells["O8"].Value = new DateTime(2010, 6, 28);
ws.Cells["K9"].Value = "Screwdriver";
ws.Cells["L9"].Value = "Hardware";
ws.Cells["M9"].Value = 1200;
ws.Cells["N9"].Value = 45.2;
ws.Cells["O9"].Value = new DateTime(2010, 8, 31);
ws.Cells["K10"].Value = "Apple";
ws.Cells["L10"].Value = "Groceries";
ws.Cells["M10"].Value = 807;
ws.Cells["N10"].Value = 1.2;
ws.Cells["O10"].Value = new DateTime(2010, 9, 30);
ws.Cells["K11"].Value = "Butter";
ws.Cells["L11"].Value = "Groceries";
ws.Cells["M11"].Value = 52;
ws.Cells["N11"].Value = 7.2;
ws.Cells["O11"].Value = new DateTime(2010, 10, 31);
ws.Cells["O2:O11"].Style.Numberformat.Format = "yyyy-MM-dd";
var pt = wsPivot1.PivotTables.Add(wsPivot1.Cells["A1"], ws.Cells["K1:N11"], "Pivottable1");
pt.Compact = true;
pt.CompactData = true;
pt.GrandTotalCaption = "Total amount";
pt.RowFields.Add(pt.Fields[1]);
pt.RowFields.Add(pt.Fields[0]);
pt.DataFields.Add(pt.Fields[3]);
pt.DataFields.Add(pt.Fields[2]);
pt.DataFields[0].Function = DataFieldFunctions.Product;
pt.DataOnRows = false;
_pck.Workbook.CreateVBAProject();
var sb = new StringBuilder();
sb.AppendLine("Private Sub Workbook_Open()");
sb.AppendLine(" Range(\"A1\").Select");
sb.AppendLine(" ActiveSheet.PivotTables(\"Pivottable1\").PivotFields(\"Category\").PivotItems(\"Hardware\").ShowDetail = False");
sb.AppendLine("End Sub");
_pck.Workbook.CodeModule.Code = sb.ToString();
_pck.Save();
}
}
}
Using EPPlus you could try something like (Taken from this SO post):
(from pf in pivot.Fields
select pf).ToList().ForEach(f =>
{
f.Compact = false;
f.Outline = false;
});
or perhaps more simply, doesn't something like the following work?
pvtTable.Compact = False
pvtTable.CompactData = False
pvtTable.Outline = False
pvtTable.OutlineData = False
pvtTable.ShowDrill = True
Also look at this SO post detailing a nice reverse engineer method for seeing how excel achieves 'things'.
P.S. Can't help you with your other 'also' question sorry.
I would like to do a plot with time function of data by using ultrachart , infragistics.
I have found this sample :
DataTable Recap = MarketData.Tables.Add("Recap");
// on ajoute des column a recap ne pas oublier de typer les colonnes
Recap.Columns.Add("Date", typeof(DateTime));
Recap.Columns.Add("Move Ticker price", typeof(double));
Recap.Columns.Add("Move Index price", typeof(double));
Recap.Columns.Add("Alpha",typeof (double));
// on remplie recap
for (int i = 0; i < TickerPrice.Rows.Count; i++)
{
DataRow destRow = Recap.NewRow();
destRow["Move Ticker price"] = TickerPrice.Rows[i]["CHG_PCT_1D"];
destRow["Move Index price"] = IndexPrice.Rows[i]["CHG_PCT_1D"];
destRow["Date"] = TickerPrice.Rows[i]["Date"];
Recap.Rows.Add(destRow);
}
// calcul du alpha
foreach (DataRow dr in Recap.Rows)
dr["Alpha"] = ((double)dr["Move Index price"]) * 1.5 - (double)dr["Move Ticker price"];
// remplir le feed alpha
FeedAlpha.DataSource = Recap;
// faire un plot
ChartPureAlpha.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.Composite;
ChartArea myChartArea = new ChartArea();
ChartPureAlpha.CompositeChart.ChartAreas.Add(myChartArea);
// Defines axes
AxisItem axisX = new AxisItem();
axisX.DataType = Infragistics.UltraChart.Shared.Styles.AxisDataType.Numeric;
axisX.Labels.ItemFormatString = "<DATA_VALUE:0.00>";
axisX.SetLabelAxisType = SetLabelAxisType.ContinuousData;
axisX.OrientationType = Infragistics.UltraChart.Shared.Styles.AxisNumber.X_Axis;
axisX.RangeType = AxisRangeType.Custom;
axisX.RangeMin = -1;
axisX.RangeMax = 1;
myChartArea.Axes.Add(axisX);
AxisItem axisY = new AxisItem();
axisY.DataType = Infragistics.UltraChart.Shared.Styles.AxisDataType.Numeric;
axisY.Labels.ItemFormatString = "<DATA_VALUE:0.00>";
axisY.Labels.HorizontalAlign = StringAlignment.Far;
axisY.SetLabelAxisType = SetLabelAxisType.ContinuousData;
axisY.OrientationType = Infragistics.UltraChart.Shared.Styles.AxisNumber.Y_Axis;
axisY.RangeType = AxisRangeType.Custom;
axisY.RangeMin = -1;
axisY.RangeMax = 1;
myChartArea.Axes.Add(axisY);
// Create and add series
XYSeries BPLseries = new XYSeries();
BPLseries.Label = "Blood L";
for (int i = 0; i < Recap.Rows.Count; i++)
BPLseries.Points.Add(new XYDataPoint((double)(Recap.Rows[i][2]), (double)Recap.Rows[i][1], "", false));
// Add a chartLayerAppearance
ChartLayerAppearance myScatterLayer = new ChartLayerAppearance();
myScatterLayer.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.ScatterChart;
myScatterLayer.ChartArea = myChartArea;
myScatterLayer.AxisX = axisX;
myScatterLayer.AxisY = axisY;
myScatterLayer.Series.Add(BPLseries);
ScatterChartAppearance sca1 = new ScatterChartAppearance();
sca1.ConnectWithLines = true;
sca1.Icon = SymbolIcon.None;
myScatterLayer.ChartTypeAppearance = sca1;
ChartPureAlpha.Series.Add(BPLseries);
ChartPureAlpha.CompositeChart.ChartLayers.Add(myScatterLayer);
CompositeLegend myLegend = new CompositeLegend();
myLegend.ChartLayers.Add(myScatterLayer);
myLegend.Bounds = new Rectangle(88, 2, 11, 15);
myLegend.BoundsMeasureType = MeasureType.Percentage;
myLegend.PE.ElementType = PaintElementType.Gradient;
myLegend.PE.FillGradientStyle = GradientStyle.ForwardDiagonal;
myLegend.PE.Fill = Color.CornflowerBlue;
myLegend.PE.FillStopColor = Color.Transparent;
myLegend.Border.CornerRadius = 10;
myLegend.Border.Thickness = 1;
ChartPureAlpha.CompositeChart.Legends.Add(myLegend);
It is working fine if I have data vs data but what I want is time (dd/mm/yyy) vs (double).
Please let me know if you have any idea.
Thanks
You can use the following code to get a time vs data chart:
using Infragistics.Win.UltraWinChart;
using Infragistics.UltraChart.Resources.Appearance;
DataTable dt = new DataTable();
dt.Columns.Add("Value", typeof(double));
dt.Columns.Add("Date", typeof(DateTime));
dt.Rows.Add(1.0, DateTime.Parse("04/20/2012"));
dt.Rows.Add(0.5, DateTime.Parse("04/21/2012"));
dt.Rows.Add(0.25, DateTime.Parse("04/22/2012"));
dt.Rows.Add(0.125, DateTime.Parse("04/23/2012"));
dt.Rows.Add(0.0625, DateTime.Parse("04/24/2012"));
dt.Rows.Add(0.03125, DateTime.Parse("04/25/2012"));
dt.Rows.Add(0.015625, DateTime.Parse("04/26/2012"));
dt.Rows.Add(0.0, DateTime.Parse("04/27/2012"));
NumericTimeSeries series = new NumericTimeSeries();
series.DataBind(dt, "Date", "Value");
UltraChart ultraChart = new UltraChart();
ultraChart.Data.SwapRowsAndColumns = true;
ultraChart.Dock = DockStyle.Fill;
ultraChart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.LineChart;
ultraChart.DataSource = dt;
this.Controls.Add(ultraChart);
How can I change the font family of the document via OpenXml ?
I tried some ways but, when I open the document, it's always in Calibri
Follow my code, and what I tried.
The Header Builder I think is useless to post
private static void BuildDocument(string fileName, List<string> lista, string tipo)
{
using (var w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
var mp = w.AddMainDocumentPart();
var d = new DocumentFormat.OpenXml.Wordprocessing.Document();
var b = new Body();
var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
var r = new Run();
// Get and format the text.
for (int i = 0; i < lista.Count; i++)
{
Text t = new Text();
t.Text = lista[i];
if (t.Text == " ")
{
r.Append(new CarriageReturn());
}
else
{
r.Append(t);
r.Append(new CarriageReturn());
}
}
// What I tried
var rPr = new RunProperties(new RunFonts() { Ascii = "Arial" });
lista.Clear();
p.Append(r);
b.Append(p);
var hp = mp.AddNewPart<HeaderPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
var sectPr = new SectionProperties();
var headerReference = new HeaderReference();
headerReference.Id = headerRelationshipID;
headerReference.Type = HeaderFooterValues.Default;
sectPr.Append(headerReference);
b.Append(sectPr);
d.Append(b);
// Customize the header.
if (tipo == "alugar")
{
hp.Header = BuildHeader(hp, "Anúncio Aluguel de Imóvel");
}
else if (tipo == "vender")
{
hp.Header = BuildHeader(hp, "Anúncio Venda de Imóvel");
}
else
{
hp.Header = BuildHeader(hp, "Aluguel/Venda de Imóvel");
}
hp.Header.Save();
mp.Document = d;
mp.Document.Save();
w.Close();
}
}
In order to style your text with a specific font follow the steps listed below:
Create an instance of the RunProperties class.
Create an instance of the RunFont class. Set the Ascii property to the desired font familiy.
Specify the size of your font (half-point font size) using the FontSize class.
Prepend the RunProperties instance to your run containing the text to style.
Here is a small code example illustrating the steps described above:
private static void BuildDocument(string fileName, List<string> text)
{
using (var wordDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
var mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var run = new Run();
foreach (string currText in text)
{
run.AppendChild(new Text(currText));
run.AppendChild(new CarriageReturn());
}
var paragraph = new Paragraph(run);
var body = new Body(paragraph);
mainPart.Document.Append(body);
var runProp = new RunProperties();
var runFont = new RunFonts { Ascii = "Arial" };
// 48 half-point font size
var size = new FontSize { Val = new StringValue("48") };
runProp.Append(runFont);
runProp.Append(size);
run.PrependChild(runProp);
mainPart.Document.Save();
wordDoc.Close();
}
}
Hope, this helps.
If you are using Stylesheet just add an instance of FontName property at appropriate font index during Fonts initilaization.
private Stylesheet GenerateStylesheet()
{
Stylesheet styleSheet = null;
Fonts fonts = new Fonts(
new Font( // Index 0 - default
new FontSize() { Val = 8 },
new FontName() { Val = "Arial"} //i.e. or any other font name as string
);
Fills fills = new Fills( new Fill(new PatternFill() { PatternType = PatternValues.None }));
Borders borders = new Borders( new Border() );
CellFormats cellFormats = new CellFormats( new CellFormat () );
styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);
return styleSheet;
}
Then use it in Workbook style part as below.
WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();