JavaFX LineChart: String values of a CategoryAxis are collapsed - javafx

I come with a question regarding a LineChart. I have a LineChart with xAxis as a CategoryAxes where I have dates and the yAxis as a NumberAxis where I have some numbers.
My problem is that on the xAxis, the values shown under the chart are overlapped and I cannot find the cause.
Here is my code where I setup the LineChart and display it:
private void createSecondLineChart(String gameName) {
xAxis2 = new CategoryAxis();
xAxis2.setLabel("Dată");
yAxis2.setLabel("Încercări");
yAxis2.setAutoRanging(false);
yAxis2.setLowerBound(0);
yAxis2.setUpperBound(10);
yAxis2.setTickUnit(2);
lineChart2.setTitle("Statistică dată/încercări");
ObservableList<XYChart.Series<String, Number>> chartData = DBUtils.getFirstGameDateStats(Stats.username,
conn);
lineChart2.setData(chartData);
for (XYChart.Series<String, Number> series : chartData) {
for (XYChart.Data<String, Number> entry : series.getData()) {
String date = String.format("Data: %s\n", entry.getXValue());
String tries = String.format("Incercari: %s\n", entry.getYValue().intValue());
double dbAvgScore = DBUtils.getAverageScoreForUserInSpecificDate(Stats.username, entry.getXValue(),
conn);
String avgScore = String.format("Punctaj mediu: %.2f", dbAvgScore);
entry.getNode().setOnMouseEntered(event -> entry.getNode().setStyle("-fx-background-color: #0084b8;"));
entry.getNode().setOnMouseExited(event -> entry.getNode().setStyle(""));
String tooltipText = date + tries + avgScore;
Tooltip t = new Tooltip(tooltipText);
t.setShowDelay(javafx.util.Duration.millis(0));
Tooltip.install(entry.getNode(), t);
}
}
lineChart2.setLegendVisible(false);
lineChart2.setVisible(true);
}

Related

How to set graph Legend position to top left in Excel in epplus

I need to set the Legend position of Graph to Top left side. But not able to set as no such property exists on eLegendPosition.
var myChart = myWorksheet.Drawings.AddChart("Chart2", eChartType.ColumnClustered) as ExcelBarChart;
**Adding an series to chart**
var serie2a = myChart.Series.Add(myWorksheet.Cells[2, 2, dataRow, 2], myWorksheet.Cells[2, 1, dataRow, 1]);
//serie2a.Header = myWorksheet.Cells[1, 2].Value.ToString();
serie2a.Header = "Plan";
myChart.YAxis.Title.Text = "Daily MH %";
myChart.YAxis.Title.Font.Size = 8;
chart2b.UseSecondaryAxis = true; //Flip the axes
chart5e.UseSecondaryAxis = true; //Flip the axes
chart2b.YAxis.Title.Text = "Cumul Daily MH %";
chart2b.YAxis.Title.Font.Size = 8;
**Here I am Facing an issue while setting it to TopLeft**
myChart.Legend.Position = eLegendPosition.Bottom;
myChart.Border.Fill.Color = System.Drawing.Color.Green;
myChart.Title.Text = "OVERALL S CURVE";
myChart.Title.Font.Size = 10;
myChart.SetSize(800, 400);
// Add to 7th row and to the 7th column
myChart.SetPosition(7, 0, 7, 0);
The enum that Epplus has matches excel so that setting alone will not do what you need. But you could manually set it in XML using a ManualLayout node:
https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.drawing.charts.manuallayout?view=openxml-2.8.1
Similar to how it was done in How to add to Text Label For excel Charts using Open xml or EPPLUS.
Here is a helper method to make it a bit more concise:
/// <summary>
/// Sets the chart's layout node <c>c:chartSpace/c:chart/c:legend/c:layout</c> for the
/// passed <see cref="ExcelBarChart"/>.
/// </summary>
/// <param name="chart">Chart to set </param>
/// <param name="x">Position X Value (percentage).</param>
/// <param name="y">Position Y Value (percentage).</param>
/// <param name="culture">Culture to use when converting the doubles to string based on excel settings.</param>
public static void SetChartManualLayout(this ExcelBarChart chart, double x, double y, CultureInfo culture)
{
//Set layout via xml
var chartXml = chart.ChartXml;
var nsm = new XmlNamespaceManager(chartXml.NameTable);
var nsuri = chartXml.DocumentElement.NamespaceURI;
nsm.AddNamespace("c", nsuri);
nsm.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
//Get the title layout and add the manual section
var layoutNode = chartXml.SelectSingleNode("c:chartSpace/c:chart/c:legend/c:layout", nsm);
var manualLayoutNode = chartXml.CreateElement("c:manualLayout", nsuri);
layoutNode.AppendChild(manualLayoutNode);
//Add coordinates
var xModeNode = chartXml.CreateElement("c:xMode", nsuri);
var attrib = chartXml.CreateAttribute("val");
attrib.Value = "edge";
xModeNode.Attributes.Append(attrib);
manualLayoutNode.AppendChild(xModeNode);
var yModeNode = chartXml.CreateElement("c:yMode", nsuri);
attrib = chartXml.CreateAttribute("val");
attrib.Value = "edge";
yModeNode.Attributes.Append(attrib);
manualLayoutNode.AppendChild(yModeNode);
var xNode = chartXml.CreateElement("c:x", nsuri);
attrib = chartXml.CreateAttribute("val");
attrib.Value = x.ToString(culture);
xNode.Attributes.Append(attrib);
manualLayoutNode.AppendChild(xNode);
var yNode = chartXml.CreateElement("c:y", nsuri);
attrib = chartXml.CreateAttribute("val");
attrib.Value = x.ToString(culture);
yNode.Attributes.Append(attrib);
manualLayoutNode.AppendChild(yNode);
}
And to use it in your code, simply do this:
// Add to 7th row and to the 7th column
myChart.SetPosition(7, 0, 7, 0);
myChart.Legend.Position = eLegendPosition.Left;
myChart.SetChartManualLayout(0.015, 0.015, CultureInfo.CurrentCulture);
Provide the X and Y as percent. 0,0 would put it at the top-left and 1,1 would put it at the bottom-right. Also, make sure to account for Culture if Excel is set differently than your app.

Create measure dictionary for area annotation in iText

The supposed value for this would is 15.2 sq cm. however, when annotation is moved, it becomes 0.04 sq cm.
I got this data from my application where area is computed as 9658.6572265625 and its calibration value is 0.00157889 which results in 15.2 value.
when the corresponding coordinates in pdf space are provided (see code below), the area computed is 5433.001953125.
so i compute the calibration value in pdf space like this.
ratio = area / pdfArea
pdfCalibrationValue = 0.00157889 * ratio;
the result is 0.002806911838696635. which if computed
5433.001953125 x 0.002806911838696635 = 15.2
so i am wondering why the result becomes 0.04.
Thoughts?
public class Test {
public static void main(String[] args) throws Exception {
PdfReader reader = new PdfReader("src.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("result.pdf"));
Rectangle location = new Rectangle(426.582f, 514.291f, 559.0f, 613.818f);
float[] floats = new float[] {
427.582f, 582.873f,
493.036f, 515.291f,
558.0f, 554.237f,
527.4f, 612.818f,
464.727f, 564.709f,
427.582f, 582.873f
};
PdfArray pdfVertices= new PdfArray(floats);
float calib = 0.002806911838696635f;
PdfAnnotation stamp = PdfAnnotation.createPolygonPolyline(stamper.getWriter(),
location, "15.2 sq cm", true, new PdfArray(pdfVertices));
stamp.setColor(BaseColor.RED);
stamp.setBorderStyle(new PdfBorderDictionary(1, PdfBorderDictionary.STYLE_SOLID));
stamp.put(PdfName.SUBTYPE, PdfName.POLYGON);
stamp.put(new PdfName("IT"), new PdfName("PolygonDimension"));
stamp.put(PdfName.MEASURE, createMeasureDictionary(calib));
stamper.addAnnotation(stamp, 1);
stamper.close();
reader.close();
}
private static PdfDictionary createMeasureDictionary(float pdfCalibrationValue) {
String unit = "cm";
PdfDictionary measureDictionary = new PdfDictionary();
measureDictionary.put(PdfName.TYPE, PdfName.MEASURE);
measureDictionary.put(PdfName.R, new PdfString("1 " + unit + " = 1 " + unit));
PdfDictionary xDictionary = new PdfDictionary();
xDictionary.put(PdfName.TYPE, PdfName.NUMBERFORMAT);
xDictionary.put(PdfName.U, new PdfString(unit));
xDictionary.put(PdfName.C, new PdfNumber(pdfCalibrationValue));
PdfArray xarr = new PdfArray();
xarr.add(xDictionary);
measureDictionary.put(PdfName.X, xarr);
PdfDictionary dDictionary = new PdfDictionary();
dDictionary.put(PdfName.TYPE, PdfName.NUMBERFORMAT);
dDictionary.put(PdfName.U, new PdfString(unit));
dDictionary.put(PdfName.C, new PdfNumber(1));
PdfArray darr = new PdfArray();
darr.add(dDictionary);
measureDictionary.put(PdfName.D, darr);
PdfDictionary aDictionary = new PdfDictionary();
aDictionary.put(PdfName.TYPE, PdfName.NUMBERFORMAT);
aDictionary.put(PdfName.U, new PdfString("sq " + unit));
aDictionary.put(PdfName.C, new PdfNumber(1));
PdfArray aarr = new PdfArray();
aarr.add(aDictionary);
measureDictionary.put(PdfName.A, aarr);
return measureDictionary;
}
}
You have calculated a factor to translate the areas:
the result is 0.002806911838696635. which if computed
5433.001953125 x 0.002806911838696635 = 15.2
But then you use this factor meant for areas unchanged as conversion factor in the X number format array.
The X number format array is the number format array for measurement of change along the x axis and, if Y is not present, along the y axis as well.
Thus, as you don't have a Y entry, your factor for areas must be the conversion factor in X squared!
In other words, use the square root of your area conversion factor as X conversion factor, i.e. replace
float calib = 0.002806911838696635f;
by
float calib = (float)Math.sqrt(0.002806911838696635);
The result now is much better:
But it is not exactly your 15.2 cm². Thus, I checked your numbers, and indeed, your value of 5433.001953125 for the polygone area is slightly off, it should be around 5388.9613.
Using this more correct value I replaced the line above again, this time by:
float calib = (float)Math.sqrt(15.2/5388.96);
and the result:

Linechart show info on point tapped

I'm implementing a little app with Xamarin Forms for a web page, the thing is that in this web is a linear chart with multiple entries and if the user clicks on a point of the line shows info about that point, as you can see in the picture:
Web Line Chart
After some work, I could create a more or less similar line chart using the OxyPlot.Xamarin.Forms plugin with multiple entries which shows the points
My App Line Chart
This is my code:
OnPropertyChanged("GraphModel");
var model = new PlotModel
{
LegendPlacement = LegendPlacement.Outside,
LegendPosition = LegendPosition.BottomCenter,
LegendOrientation = LegendOrientation.Horizontal,
LegendBorderThickness = 0
};
model.PlotType = PlotType.XY;
model.InvalidatePlot(false);
Dictionary<string, List<Prices>> values = HistoricData[Selected.ProductId];
int colorIndex = 0;
List<string> x_names = new List<string>();
foreach (var item in values.Keys)
{
if (item.ToUpper() == Selected.ProductName) { SelectedIndex = colorIndex; }
var lineSeries = new LineSeries()
{
Title = item,
MarkerType = MarkerType.Circle,
};
lineSeries.MarkerResolution = 3;
lineSeries.MarkerFill = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerStroke = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerSize = 3;
var points = new List<DataPoint>();
lineSeries.Color = OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
foreach (var price in values[item])
{
points.Add(new DataPoint(price.Week+price.Year, price.Price));
}
if (ButtonsVisibility.Count == 0)
{
lineSeries.IsVisible = (Selected.ProductName == item.ToUpper()) ? true : false;
}
else
{
lineSeries.IsVisible = ButtonsVisibility[colorIndex];
}
lineSeries.ItemsSource = points;
lineSeries.MarkerType = OxyPlot.MarkerType.Circle;
model.Series.Add(lineSeries);
colorIndex++;
}
NumButtons = colorIndex;
LinearAxis yaxis = new LinearAxis();
yaxis.Position = AxisPosition.Left;
yaxis.MajorGridlineStyle = LineStyle.Dot;
model.Axes.Add(yaxis);
LineChart = model;
OnPropertyChanged("GraphModel");
return LineChart;
My doubt is which property I should work with and show at least the value of a concrete point, I have seen the property OnTouchStarted but is only for all the LineSeries and not for a single point. I read in some articles that OxyPlot.Xamarin.Forms include a tracker. I added this line in my code:
lineSeries.TrackerFormatString = "X={2},\nY={4}";
Is supposed to show the x and y values on click but doesn't show anything, any suggestion?
Should show something like that: Tracker info on point
From the following example: Tracker Example
Updated Code
public PlotModel GetLineChart()
{
OnPropertyChanged("GraphModel");
var model = new PlotModel
{
LegendPlacement = LegendPlacement.Outside,
LegendPosition = LegendPosition.BottomCenter,
LegendOrientation = LegendOrientation.Horizontal,
LegendBorderThickness = 0
};
model.PlotType = PlotType.XY;
model.InvalidatePlot(false);
Dictionary<string, List<Prices>> values = HistoricData[Selected.ProductId];
int colorIndex = 0;
List<string> x_names = new List<string>();
foreach (var item in values.Keys)
{
if (item.ToUpper() == Selected.ProductName) { SelectedIndex = colorIndex; }
var lineSeries = new LineSeries()
{
Title = item,
MarkerType = MarkerType.Circle,
CanTrackerInterpolatePoints = false
};
lineSeries.MarkerResolution = 3;
lineSeries.MarkerFill = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerStroke = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
lineSeries.MarkerSize = 3;
var points = new List<DataPoint>();
lineSeries.Color = OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
foreach (var price in values[item])
{
points.Add(new DataPoint(price.Week+price.Year, price.Price));
}
if (ButtonsVisibility.Count == 0)
{
lineSeries.IsVisible = (Selected.ProductName == item.ToUpper()) ? true : false;
}
else
{
lineSeries.IsVisible = ButtonsVisibility[colorIndex];
}
lineSeries.ItemsSource = points;
lineSeries.MarkerType = OxyPlot.MarkerType.Circle;
lineSeries.TrackerFormatString = "X={2},\nY={4}";
lineSeries.TextColor = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
model.Series.Add(lineSeries);
colorIndex++;
}
NumButtons = colorIndex;
LinearAxis yaxis = new LinearAxis();
yaxis.Position = AxisPosition.Left;
//yaxis.StringFormat = "X={2},\nY={4}";
yaxis.MajorGridlineStyle = LineStyle.Dot;
model.Axes.Add(yaxis);
LineChart = model;
OnPropertyChanged("GraphModel");
return LineChart;
}
}
protected async override void OnAppearing()
{
await _viewModel.LinearViewModel.GetSubCategoryHistoricWeekPrices(App.ViewModel.LoginViewModel.SesionToken, FROM_DATE, TO_DATE);
Plot.Model = _viewModel.LinearViewModel.GetLineChart();
PlotController controller = new PlotController();
controller.UnbindAll();
controller.BindTouchDown(PlotCommands.PointsOnlyTrackTouch);
Plot.Controller = controller;
AddButtons();
}
Xaml Declaration for plot view:
<oxy:PlotView
Grid.Row="2"
Grid.RowSpan="2"
Grid.ColumnSpan="4"
x:Name="Plot" />
Your problem lies with following line.
lineSeries.TrackerKey = "X={2},\nY={4}";
When you use series.TrackerKey, you are specifying that you are using a CustomTracker, which in this case you are not. Custom trackers would be useful if you need to use different trackers for each series in the model.
In you case, you should remove that line and use only TrackerFormatString.
lineSeries.TrackerFormatString = "X={2},\nY={4}";
This would show the tooltip using the format string parameters, where {2} signifies X Value and {4} signifies Y. For your information, following are place holders.
{0} = Title of Series
{1} = Title of X-Axis
{2} = X Value
{3} = Title of Y-Axis
{4} = Y Value
If you need to include additional/custom information in your tool, your Data Point needs to be include that information. This where IDataPointProvider interface becomes handy. You could create a Custom DataPoint by implementing the interface and then you could include the same information in your tooltip as well.
Update Based On Comments
Additionally, to include "Touch", you can specify TouchDown in the PlotController. You can do so by defining the PlotController in your viewModel as following.
public PlotController CustomPlotController{get;set;}
You can define the property as follows.
CustomPlotController = new PlotController();
CustomPlotController.UnbindAll();
CustomPlotController.BindTouchDown(PlotCommands.PointsOnlyTrackTouch);
And in your Xaml
<oxy:Plot Controller="{Binding CustomPlotController}"......

Weird TableView error while getting data from different models

I'm working on a TableView who should display data from different kind of models. When I use one model everything works fine. But as soon as I add other models it turns out erroneous at OPTable.getColumns().addAll(...); . I can't make sense of the error description.
The method addAll(int, Collection<? extends TableColumn<capture#4-of ?,?>>) in the type List<TableColumn<capture#4-of ?,?>> is not applicable for the arguments (TableColumn<Ofenproben,String>, TableColumn<Ofenproben,String>, TableColumn<Auftrag,String>, TableColumn<Ofenproben,String>, TableColumn<ModelConverter,String>, TableColumn<ModelConverter,String>, TableColumn<ModelConverter,String>)
Here is my TableView:
TableView<?> OPTable= new TableView();
OPTable.setEditable(true);
OPTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
OPTable.setColumnResizePolicy((param) -> true );
TableColumn<Ofenproben, String> TLPCol = new TableColumn<Ofenproben, String>("TLP Typ");
TableColumn<Ofenproben, String> LosCol= new TableColumn<Ofenproben, String>("Losbezeichnung");
TableColumn<Auftrag, String> AKBCol = new TableColumn<Auftrag, String>("Auftragskurzbezeichnung");
AKBCol.setPrefWidth(350);
TableColumn<Ofenproben, String> ProbenNrCol = new TableColumn<Ofenproben, String>("Probennummer");
TableColumn<ModelConverter, String> OfenCol = new TableColumn<ModelConverter, String>("Ofen");
TableColumn<ModelConverter, String> PlatzNrCol = new TableColumn<ModelConverter, String>("Platz");
TableColumn<ModelConverter, String> ProbeFertigCol = new TableColumn<ModelConverter, String>("Proben fertig");
//Sub Columns
TableColumn<ModelConverter, Boolean> EinsCol = new TableColumn<ModelConverter, Boolean>("1");
TableColumn<ModelConverter, Boolean> ZweiCol = new TableColumn<ModelConverter, Boolean>("2");
TableColumn<ModelConverter, Boolean> DreiCol = new TableColumn<ModelConverter, Boolean>("3");
TableColumn<ModelConverter, Boolean> VierCol = new TableColumn<ModelConverter, Boolean>("4");
// Sub columns an Proben Fertig anfügen
ProbeFertigCol.getColumns().addAll(EinsCol, ZweiCol, DreiCol, VierCol);
//Daten einfügen von Klasse Ofenproben
TLPCol.setCellValueFactory(new PropertyValueFactory<>("TLP"));
LosCol.setCellValueFactory(new PropertyValueFactory<>("Los"));
AKBCol.setCellValueFactory(new PropertyValueFactory<>("AKB"));
ProbenNrCol.setCellValueFactory(new PropertyValueFactory<>("ProbenNr"));
OfenCol.setCellValueFactory(new PropertyValueFactory<>("Ofen"));
OfenCol.setCellFactory(TextFieldTableCell.<ModelConverter> forTableColumn());
OfenCol.setOnEditCommit((CellEditEvent<ModelConverter, String> event) -> {
TablePosition<ModelConverter, String> pos = event.getTablePosition();
String newOfen = event.getNewValue();
int row = pos.getRow();
ModelConverter mc = event.getTableView().getItems().get(row);
mc.setOfen(newOfen);
});
PlatzNrCol.setCellValueFactory(new PropertyValueFactory<>("PlatzNr"));
PlatzNrCol.setCellFactory(TextFieldTableCell.<ModelConverter> forTableColumn());
PlatzNrCol.setOnEditCommit((CellEditEvent<ModelConverter, String> event) -> {
TablePosition<ModelConverter, String> pos = event.getTablePosition();
String newStellplatz = event.getNewValue();
int row = pos.getRow();
ModelConverter mc = event.getTableView().getItems().get(row);
mc.setStellplatz(newStellplatz);
});
EinsCol.setCellValueFactory(new PropertyValueFactory<>("checked"));
ZweiCol.setCellValueFactory(new PropertyValueFactory<>("checked"));
DreiCol.setCellValueFactory(new PropertyValueFactory<>("checked"));
VierCol.setCellValueFactory(new PropertyValueFactory<>("checked"));
EinsCol.setCellFactory(CheckBoxTableCell.forTableColumn(EinsCol));
ZweiCol.setCellFactory(CheckBoxTableCell.forTableColumn(ZweiCol));
DreiCol.setCellFactory(CheckBoxTableCell.forTableColumn(DreiCol));
VierCol.setCellFactory(CheckBoxTableCell.forTableColumn(VierCol));
//ObservableList<ModelConverter> list = getProbenList();
//OPTable.setItems(list);
OPTable.getColumns().addAll(TLPCol, LosCol, AKBCol, ProbenNrCol, OfenCol, PlatzNrCol, ProbeFertigCol);
Please help and give me an code example to solve this problem.

Getting an Error Meassage "System.IO.FileFormatException: Compressed part has inconsistent data length" calling XmlDocument.Load()

I'm new to OpenXML,here i'm trying to export chart data to powerpoint.Here in the code i trying to save it as excel file and then to powerpoint,while trying click on the export button it showing me an error message(Written as aheading).here i'm my code.
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
// Open an existing Presentation
PresentationDocument oPDoc = PresentationDocument.Open(#"D:\Chart.pptx", true);
PresentationPart oPPart = oPDoc.PresentationPart;
// Get the ReleationshipId of the first Slide
SlideId slideId = oPPart.Presentation.SlideIdList.GetFirstChild<SlideId>();
string relId = slideId.RelationshipId;
// Get the slide part by the relationship ID.
SlidePart slidePart = (SlidePart)oPPart.GetPartById(relId);
// Add a new chart part
ChartPart chPrt = slidePart.AddNewPart<ChartPart>();
XmlDocument xDoc = new XmlDocument();
String strFileName = "D:\\chart1.xml";
xDoc.Load(strFileName);
StreamWriter objDocMainWrt = new StreamWriter(chPrt.GetStream(FileMode.Create, FileAccess.Write));
xDoc.Save(objDocMainWrt);
// Add the data Sheet for the Chart
ExtendedPart objEmbPart = chPrt.AddExtendedPart("http://schemas.openxmlformats.org/officeDocument/2006/relationships/package", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx");
strFileName = "D:\\chartData.xlsx";
FileStream partStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
objEmbPart.FeedData(partStream);
// Change the Data releation ID used in Chart.xml
// Elemenet changed : c:externalData
string relChtDataID = chPrt.GetIdOfPart(objEmbPart);
XmlNamespaceManager nsManager1 = new XmlNamespaceManager(xDoc.NameTable);
XmlNamespaceManager nsManagerDraw = new XmlNamespaceManager(xDoc.NameTable);
//nsManager1.AddNamespace("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
nsManagerDraw.AddNamespace("d", "http://schemas.openxmlformats.org/drawingml/2006/chart");
//XmlNodeList nodeTest = xDoc.SelectNodes("//c:externalData", nsManager1);
XmlNodeList nodeTest = xDoc.SelectNodes("//d:chart1", nsManagerDraw);
foreach (XmlNode node in nodeTest)
{
node.Attributes["r:id"].Value = relChtDataID;
}
// Save changes back to Chart.xml
xDoc.Save(chPrt.GetStream(FileMode.Create, FileAccess.Write));
// Get the SlidePart Stream
const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("p", presentationmlNamespace);
XmlDocument presXML = new XmlDocument(nt);
presXML.Load(slidePart.GetStream());
// Get the spTree Element in SlidePart
XmlNode nodeTree = presXML.SelectSingleNode("//p:spTree", nsManager);
string rid = slidePart.GetIdOfPart(chPrt).ToString();
// Generate the Graphic Element for the Chart
XmlNode childNode = GenerateNode(rid);
//Append the Graphic Element to spTree Element in SlidePart
nodeTree.AppendChild(presXML.ImportNode(childNode, true));
Stream o = slidePart.GetStream();
presXML.Save(o);
oPDoc.Close();
}
catch (Exception msg)
{
Response.Write(msg.ToString());
}
}
private XmlNode GenerateNode(String rId)
{
XmlDocument xwb = new XmlDocument();
xwb.AppendChild(xwb.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
XmlNamespaceManager xmlns = new XmlNamespaceManager(xwb.NameTable);
xmlns.AddNamespace("p", "http://schemas.openxmlformats.org/presentationml/2006/main");
xmlns.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
xmlns.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
XmlElement eleGraphic = xwb.CreateElement("p:graphicFrame", xmlns.LookupNamespace("p"));
xwb.AppendChild(eleGraphic);
XmlElement eleGrpFrm = xwb.CreateElement("p:nvGraphicFramePr", xmlns.LookupNamespace("p"));
eleGraphic.AppendChild(eleGrpFrm);
XmlElement elePpr = xwb.CreateElement("p:cNvPr", xmlns.LookupNamespace("p"));
eleGrpFrm.AppendChild(elePpr);
XmlAttribute attrRid = xwb.CreateAttribute("id");
attrRid.Value = "4";
elePpr.SetAttributeNode(attrRid);
XmlAttribute attrName = xwb.CreateAttribute("name");
attrName.Value = "Chart 2";
elePpr.SetAttributeNode(attrName);
XmlElement elecNvGraphicFramePr = xwb.CreateElement("p:cNvGraphicFramePr", xmlns.LookupNamespace("p"));
eleGrpFrm.AppendChild(elecNvGraphicFramePr);
XmlElement elenvPr = xwb.CreateElement("p:nvPr", xmlns.LookupNamespace("p"));
eleGrpFrm.AppendChild(elenvPr);
XmlElement elexfrm = xwb.CreateElement("p:xfrm", xmlns.LookupNamespace("p"));
eleGraphic.AppendChild(elexfrm);
XmlElement eleoff = xwb.CreateElement("a:off", xmlns.LookupNamespace("a"));
elexfrm.AppendChild(eleoff);
XmlAttribute xvalue = xwb.CreateAttribute("x");
xvalue.Value = "1524000";
eleoff.SetAttributeNode(xvalue);
XmlAttribute yvalue = xwb.CreateAttribute("y");
yvalue.Value = "1397000";
eleoff.SetAttributeNode(yvalue);
XmlElement eleext = xwb.CreateElement("a:ext", xmlns.LookupNamespace("a"));
elexfrm.AppendChild(eleext);
XmlAttribute cxvalue = xwb.CreateAttribute("cx");
cxvalue.Value = "6096000";
eleext.SetAttributeNode(cxvalue);
XmlAttribute cyvalue = xwb.CreateAttribute("cy");
cyvalue.Value = "4064000";
eleext.SetAttributeNode(cyvalue);
//<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:id="rId2"/></a:graphicData></a:graphic></p:graphicFrame>
XmlElement elegraphic = xwb.CreateElement("a:graphic", xmlns.LookupNamespace("a"));
eleGraphic.AppendChild(elegraphic);
XmlElement elegraphicData = xwb.CreateElement("a:graphicData", xmlns.LookupNamespace("a"));
elegraphic.AppendChild(elegraphicData);
XmlAttribute uri = xwb.CreateAttribute("uri");
uri.Value = "http://schemas.openxmlformats.org/drawingml/2006/chart";
elegraphicData.SetAttributeNode(uri);
XmlElement elechart = xwb.CreateElement("c:chart", "http://schemas.openxmlformats.org/drawingml/2006/chart");
elegraphicData.AppendChild(elechart);
XmlAttribute id = xwb.CreateAttribute("r:id", xmlns.LookupNamespace("r"));
id.Value = rId;
elechart.SetAttributeNode(id);
XmlNode ss1 = xwb.SelectSingleNode("//p:graphicFrame", xmlns);
return ss1;
//xwb.Save(#"C:\temp\test1.xml");
}
Please let me know where i have done mistake.
Try this below code,before that create empty ppt template and excel with two chart controls.
string paramPresentationPath = #"D:\Chart.pptx";
string paramWorkbookPath = #"D:\chartData.xlsx";
object paramMissing = Type.Missing;
powerpointApplication = new pptNS.Application();
// Create an instance Excel.
excelApplication = new xlNS.Application();
// Open the Excel workbook containing the worksheet with the chart
// data.
excelWorkBook = excelApplication.Workbooks.Open(paramWorkbookPath,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing, paramMissing,
paramMissing, paramMissing);
// Get the worksheet that contains the chart.
targetSheet = (xlNS.Worksheet)(excelWorkBook.Worksheets[1]);//here 1 is sheet no.
// Get the ChartObjects collection for the sheet.
chartObjects = (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));
// Get the chart to copy.
existingChartObject = (xlNS.ChartObject)(chartObjects.Item("Chart Name in Excel"));
// Create a PowerPoint presentation.
pptPresentation = powerpointApplication.Presentations.Add(
Microsoft.Office.Core.MsoTriState.msoTrue);
// Add a blank slide to the presentation.
pptSlide = pptPresentation.Slides.Add(1, pptNS.PpSlideLayout.ppLayoutBlank);
// Copy the chart from the Excel worksheet to the clipboard.
existingChartObject.Copy();
// Paste the chart into the PowerPoint presentation.
shapeRange = pptSlide.Shapes.Paste();
// Position the chart on the slide.
shapeRange.Left = 30;
shapeRange.Top = 100;
// Width and Height on the Slide.
shapeRange.Width = 600;
shapeRange.Height = 400;
///<summary>
///Second Slide
///</summary>
// Get the worksheet that contains the chart.
targetSheet = (xlNS.Worksheet)(excelWorkBook.Worksheets[2]);
// Get the ChartObjects collection for the sheet.
chartObjects = (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));
// Get the chart to copy.
existingChartObject = (xlNS.ChartObject)(chartObjects.Item("Chart Name in excel"));
//// Create a PowerPoint presentation.
//pptPresentation = powerpointApplication.Presentations.Add(
// Microsoft.Office.Core.MsoTriState.msoTrue);
// Add a blank slide to the presentation.
pptSlide = pptPresentation.Slides.Add(2, pptNS.PpSlideLayout.ppLayoutBlank);
// Copy the chart from the Excel worksheet to the clipboard.
existingChartObject.Copy();
// Paste the chart into the PowerPoint presentation.
shapeRange = pptSlide.Shapes.Paste();
// Position the chart on the slide.
shapeRange.Left = 30;
shapeRange.Top = 100;
// Width and Height on the Slide.
shapeRange.Width = 600;
shapeRange.Height = 400;
// Save the presentation.
pptPresentation.SaveAs(paramPresentationPath,
pptNS.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
Microsoft.Office.Core.MsoTriState.msoTrue);
//pptPresentation.Close();
}
catch (Exception msg)
{
Response.Write(msg.ToString());
}
finally
{
shapeRange = null;
pptSlide = null;
object paramMissing = Type.Missing;
// Close and release the Presentation object.
if (pptPresentation != null)
{
pptPresentation.Close();
Marshal.FinalReleaseComObject(pptPresentation);
//Marshal.ReleaseComObject(pptPresentation.Slides);
pptPresentation = null;
}
// Quit PowerPoint and release the ApplicationClass object.
if (powerpointApplication != null)
{
powerpointApplication.Quit();
Marshal.FinalReleaseComObject(powerpointApplication);
powerpointApplication = null;
}
// Release the Excel objects.
targetSheet = null;
chartObjects = null;
existingChartObject = null;
//Close and release the Excel Workbook object.
if (excelWorkBook != null)
{
excelWorkBook.Close(false, paramMissing, paramMissing);
Marshal.FinalReleaseComObject(excelWorkBook);
excelWorkBook = null;
}
// Quit Excel and release the ApplicationClass object.
if (excelApplication != null)
{
excelApplication.Quit();
Marshal.FinalReleaseComObject(excelApplication);
excelApplication = null;
//System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
}
////releaseObject(ref excelApplication);
////releaseObject(ref powerpointApplication);
System.Diagnostics.Process[] excelprc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
if (excelprc.Length == 1)
{
excelprc[0].Kill();
}
System.Diagnostics.Process[] ppprc = System.Diagnostics.Process.GetProcessesByName("POWERPNT");
if (ppprc.Length == 1)
{
ppprc[0].Kill();
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

Resources