Home > database >  remove specific legend apache poi excel graph XDDFChartLegend
remove specific legend apache poi excel graph XDDFChartLegend

Time:10-06

i am using apache poi 5.0.0 version i have generated a graph in excel using the data and i am able to see the legends in the bottom of the graph. There are six legends shown. Now i want to remove two specific legends without removing them from the graph.

enter image description here

There seems to be no functions available in XDDFChartLegend which really works. say for example

XDDFChartLegend  legend = chart.getOrAddLegend();
legend.getEntries().remove(4);

doesnt work

Any help would be appreciated.

CodePudding user response:

A chart legend entry cannot be removed. It only can be marked deleted, so it will not be shown.

XDDFLegendEntry provides method setDelete to do so. But the problem is how to get the XDDFLegendEntry.

XDDFChart.getOrAddLegend only adds an empty legend marker which uses defaults for showing the legend. There are no legend entries by default as those only are needed to set special properties which are not default. So we would need someting like XDDFChartLegend.getOrAddLegendEntry to get or add a legend entry. This does not exist until now.

Following method gets or adds a legend entry to a given XDDFChartLegend for a given index.

 XDDFLegendEntry getOrAddLegendEntry(XDDFChartLegend legend, int index) {
  XDDFLegendEntry legendEntry = null;
  try {
   legendEntry = legend.getEntry(index);
  } catch (IndexOutOfBoundsException iOoBex) {
   //this legend entry does not exist, do nothing, legendEntry stays null     
  }
  if (legendEntry == null) {
   legendEntry = legend.addEntry();
   legendEntry.setIndex(index); 
  }
  return legendEntry;
 } 

Usage to mark legend entry as deleted could be as so:

...
   XDDFChartLegend legend = chart.getOrAddLegend();
   //...
   XDDFLegendEntry legendEntry = getOrAddLegendEntry(legend, 4);
   legendEntry.setDelete(true);
...
  • Related