Creating a X x Y chart in Excel with C# - c#

I'm trying to create a chart in Excel with C#. What I did so far is populating an Excel spreadsheet with the data I need to plot. I Have data on my spreadsheet that looks like this:
T U
10 10
20 5
30 3,333333333
40 2,5
50 2
60 1,666666667
70 1,428571429
80 1,25
90 1,111111111
100 1
110 0,909090909
120 0,833333333
130 0,769230769
140 0,714285714
150 0,666666667
160 0,625
I have data from line 1 to line 40.
I want to create a chart in Excel like this one:
Notice that on the X axis, I want to put the values (or some of the values) from column T, and in the Y axis, the values from the U column.
I made the following code to create a chart:
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
Microsoft.Office.Interop.Excel.Range chartRange;
Microsoft.Office.Interop.Excel.ChartObjects xlCharts = (Microsoft.Office.Interop.Excel.ChartObjects)ws.ChartObjects(Type.Missing);
Microsoft.Office.Interop.Excel.ChartObject myChart = (Microsoft.Office.Interop.Excel.ChartObject)xlCharts.Add(240, 90, 468, 315);
Microsoft.Office.Interop.Excel.Chart chartPage = myChart.Chart;
chartRange = ws.get_Range("U1", "U40");
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
which got me the following result:
which is pretty close to what I need, but I couldn't set the values for the X axis.
Can someone please tell me how to assign the values from the range T1 to T40 to the X axis?
And if possible, how can I remove the label "Série 1" from the chart?

This is six months old, so I imagine that you've already moved on, but:
You've already got a reference to the chart (chartPage), so setting the x-axis values and removing the legend should be simple. You just need a reference to the series itself.
Excel.Series ser = (Excel.Series)chartPage.SeriesCollection(1);
ser.xValues = ws.Range[ws.cells[row,col],ws.cells[row,col]];
chartPage.hasLegend = false;
This was written assuming that you've aliased Microsoft.Office.Interop.Excel like this:
using Excel = Microsoft.Office.Interop.Excel;
and that the series you're working on is actually the first one. You could also set the y-values the same way, instead of setting the source data.
ser.Values = ws.Range[etc...];

Related

Change bar chart axis scale using Aspose.Cells for C#

I'm trying to set the axis scale for a bar chart using Aspose.Cells for C#. What I'm currently doing is essentially this:
var chart = worksheet.Charts.Add(ChartType.BarChart, 1, 1, 15, 15)
chart.NSeries.AddSeries("{.015,.03,.04}", true)
chart.NSeries.CategoryData = "{Apples,Oranges,Pears}"
chart.SeriesAxis.IsAutomaticMajorUnit = false;
chart.SeriesAxis.MajorUnit = .01;
However, when the spreadsheet renders the chart's major unit scale is automatically set to .1, so all the bars look disproportionately small. How can I change the scale of the series axis, so it has tick marks spaced apart by .01?
Please use the following code for your needs.
C#
//Set the major unit to 0.01
ch.ValueAxis.IsAutomaticMajorUnit = false;
ch.ValueAxis.MajorUnit = 0.01;
Here is the full sample code and the screenshot showing the output Excel file generated by the code for your reference.
C#
// Create empty workbook.
Workbook wb = new Workbook();
// Access first worksheet.
Worksheet worksheet = wb.Worksheets[0];
// Add Bar chart in first worksheet.
int idx = worksheet.Charts.Add(ChartType.Bar, 5, 2, 20, 10);
// Access Bar chart.
Chart ch = worksheet.Charts[0];
// Add two number series, true means they are vertical.
ch.NSeries.Add("{.015,.03,.04}", true);
// Set the category data to show on X-axis.
ch.NSeries.CategoryData = "{Apples,Oranges,Pears}";
// Set the name of first and second series.
ch.NSeries[0].Name = "Cricket";
//Set the major unit to 0.01
ch.ValueAxis.IsAutomaticMajorUnit = false;
ch.ValueAxis.MajorUnit = 0.01;
// Save the output in xlsx format.
wb.Save("outputBarChart.xlsx", SaveFormat.Xlsx);
Note: I am working as Developer Evangelist at Aspose

How can I set an exact size (in centimeters) for an Excel cell programatically (C#)?

I intend to write some information to Excel from C#. The code I am using is:
var oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
var oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
var oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oSheet.Columns.ColumnWidth = 5;
oSheet.Rows.RowHeight = 5;
oSheet.Cells[1, 1] = "Smith";
...
The problem is that I need to set an exact size in centimeters (5) for all the cells. The ColumnWidth property receives the number of points and not centimeters. In various articles I found that 1 point = 0.035cm, meaning that 1cm = 28.57p, but when I pass 5*28.57 for ColumnWidth and for RowHeight, Excel's columns are set to 28.58cm and rows are set to 5.04cm.
How can I solve this case?
Thank you,
The column width in Excel is specified in "Characters", not "Points". The default column width is 8.37 "Characters", 1 character being the width of the 1 character of the default font used to display normal text in Excel.
In order to specify the column width in cm, you need to first convert cm to points using the following function:
double x = xl.Application.CentimetersToPoints(5);
Then use one loop to repeatedly decrease the column width by 0.1 points until it matches the number of points (x). (For columns whose width is greater than 'x' points)
while(ws.Columns.ColumnWidth - 0.1 > points)
{
ws.Columns.ColumnWidth = ws.Columns.ColumnWidth - 0.1;
}
Then use another loop to repeatedly increase the column width by 0.1 points until it matches the number of points (x). (For columns whose width is lesser than 'x' points)
while(ws.Columns.ColumnWidth + 0.1 < points)
{
ws.Columns.ColumnWidth = ws.Columns.ColumnWidth + 0.1;
}
The above method takes a few seconds to execute because of the loops. However, it achieves the solution (setting column width in cm).
Note: In the above code,
xl : Excel application object
ws : Worksheet object

Excel Chart Type vertical value

From a long time i am trying to generate graph like this
Codes i tried.
Excel.Range chartRange1;
Excel.ChartObjects xlCharts1 = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart1 = (Excel.ChartObject)xlCharts1.Add(350, 500, 500, 350);
Excel.Chart chartPage1 = myChart1.Chart;
chartRange1 = worksheet.get_Range("A33", "b56");
chartPage1.SetSourceData(chartRange1, Type.Missing);
chartPage1.ChartType = Excel.XlChartType.xlBarStacked;
Excel.Range xValues = worksheet.Range["B33", "B56"];
Excel.Range values = worksheet.Range["a33", "a56"];
Excel.SeriesCollection seriesCollection = (Excel.SeriesCollection)chartPage1.SeriesCollection();
Excel.Series series1 = seriesCollection.NewSeries();
series1.XValues = xValues;
series1.Values = values;
Please help which chart type i should use or i am making any mistake. A
After changing chart type, it works perfectly fine but its not working for last row text. As shown in image below.
Yes, you need to change the chart type.
using Excel = Microsoft.Office.Interop.Excel;
chartPage1.ChartType = Excel.XlChartType.xlBarClustered
You may have to adjust gridlines depending on how you want them to appear. I can provide more code for that if needed.
Edit - Also, don't forget to do
chartPage1.PlotBy = Excel.XlRowCol.xlColumns;
I don't know how but the moment i commented chartPage1.SetSourceData(chartRange1, Type.Missing); in code it works fine, might be possible two data source are set one by commented line and one by series collection.

How do I add additional series to a Excel Chart using C#

I am trying to add an additional data series to the chart this shows CPU threshold, I can get the range and create the graph with out the threshold on it, but I don't know how to add the threshold value to the chart.
do I need to create another chart object? can I use the existing and just add teh new range in?
How are you creating the chart? -- see code below.
Is this chart already created in the excel file, and you want to modify the chart in the excel file? yes the chart is already in a Excel file.
Excel.ChartObjects sCPUChart;
Excel.ChartObject sCPUChartObjects;
sCPUChart = sDBSheet.ChartObjects(Type.Missing);
sCPUChartObjects = sCPUChart.Add(49, 15, 360, 215);
Excel.Chart sChartCPU;
sChartCPU = sCPUChartObjects.Chart;
sChartCPU.SetSourceData(cpuChartRange, Missing.Value);
sChartCPU.ChartWizard(Source: cpuChartRange, Gallery: Excel.XlChartType.xlLine, Format: 2, HasLegend: true);
sChartCPU.Location(Excel.XlChartLocation.xlLocationAsObject, sDBSheet.Name);
//CPU Chart Axis
Excel.Axis xSChartCPUAxis;
xSChartCPUAxis = sChartCPU.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
Excel.Axis ySChartCPUAxis;
ySChartCPUAxis = syChartCPU.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
ySChartCPUAxis.HasMajorGridlines = true;
ySChartCPUAxis.MaximumScaleIsAuto = true;
//Set Summary CPU Series
Excel.Series sCPUSeries = sChartCPU.SeriesCollection(1);
sCPUSeries.Name = "CPU";
//-------
// this is where I am having my issue
//I don't know how to add the threshold line to the graph with the existing graph being displayed
//sChartCPU.set_HasAxis(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlSecondary, true);
//summaryChartCPU.SetSourceData(summaryMemThreshold, Type.Missing); -- things break
//-------
I have now done the following:
Excel.SeriesCollection threshold = sChartCPU.sseriesCollection();
Excel.Series line = threshold.NewSeries();
line.Formula = "=SERIES(Summ!$D$54,Summ!$C$55:$C$56,Summ!$D$55:$D$56)";
line.ChartType = Excel.XlChartType.xLScatterLinesNoMarkers;
when the threshold line is created I have the following
the values I have in cells D54 - threshold
C55 = 0
C56 = 1
D55 = 75
D56 = 75
I don't know how to remove the 2 additional axis that appear in chart
If I comment out the line.ChartType, then the axis is correct but I only get one threshold data point ?? I don't understand why.
var series = (SeriesCollection) yourChart.SeriesCollection();
var line = series.NewSeries();
line.Name = "CPU Threshhold";
//line.Values = ...;
//line.XValues = ...;
//formatting
Here's the solution I found to the OP's question of how to remove the secondary axes:
Excel.SeriesCollection threshold = sChartCPU.sseriesCollection();
Excel.Series line = threshold.NewSeries();
// line.Formula = "=SERIES(Summ!$D$54,Summ!$C$55:$C$56,Summ!$D$55:$D$56)";
// instead of setting the Formula, I set the series values
line.Values = "='Summ!'$D$55:$D$56";
line.XValues = "='Summ!'$C$55:$C$56";
line.ChartType = Excel.XlChartType.xlXYScatterLinesNoMarkers;
// creates Axis objects for the secondary axes
Excel.Axis YAxis2 = (Excel.Axis)sChartCPU.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlSecondary);
Excel.Axis XAxis2 = (Excel.Axis)sChartCPU.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlSecondary);
// remove the major and minor tick marks from the secondary (top) x-axis
XAxis2.MajorTickMark = Excel.XlTickMark.xlTickMarkNone;
XAxis2.MinorTickMark = Excel.XlTickMark.xlTickMarkNone;
// change the secondary x-axis max range to 1.0 so the bar will go all the way to the right side
XAxis2.MaximumScale = 1.0;
// delete the secondary x-axis labels
XAxis2.TickLabels.Delete();
// I chose to delete the secondary y-axis so the line would graph on the primary axis scale
YAxis2.Delete();

C# show chart values on chart top

I have created the chart using C# interop. I want to show the exact values on tip of the bar chart. How can I do it? My code is here.
Range chartRange;
Object misValue = System.Reflection.Missing.Value;
ChartObjects xlCharts = (ChartObjects)sheet0.ChartObjects(Type.Missing);
ChartObject myChart = (ChartObject)xlCharts.Add(10, 70, 250, 250);
Chart chartPage = myChart.Chart;
chartRange = sheet0.get_Range("$G$2:$G$12,$AB$2:$AB$12,$AT$2:$AT$12", misValue);
SeriesCollection scl = myChart.Chart.SeriesCollection();
Series xlSeries = scl.NewSeries();
chartPage.SetSourceData(chartRange, misValue);
xlSeries.XValues = sheet0.get_Range("A3:A12");
chartPage.ChartType = XlChartType.xlColumnClustered;
chartPage.Location(XlChartLocation.xlLocationAsNewSheet, "Islamic Summary Chart");
Please help me get the values on tip of the chart.
Thank you.
I don't think you can easily put them on the top on a clustered column chart.
DataLabels.Position
property is the one to look at, but even the
XlDataLabelPosition.xlLabelPositionAbove;
won't work for your type of chart.
One solution for you is to add another series as a XY scatter chart type, hide the points and display the data labels on that series since you can display it above the points. The values can be exactly the same as you have them now.

Categories

Resources