Skip to content
Advertisement

remove specific legend apache poi excel graph XDDFChartLegend

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.

Advertisement

Answer

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, long index) {
  XDDFLegendEntry legendEntry = null;
  for (XDDFLegendEntry storedLegendEntry : legend.getEntries()) {
   if (storedLegendEntry.getIndex() == index) {
    legendEntry = storedLegendEntry;
    break;
   }   
  }
  if (legendEntry == null) {
   legendEntry = legend.addEntry();
   legendEntry.setIndex(index); 
  }
  return legendEntry;
 } 

Note, I do not use XDDFChartLegend.getEntry as this returns the entry at position index rather than the entry having the index index. But we need the entry having the index index. So I loop over all entries and do check whether there is one having the index already.

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

...
   XDDFChartLegend legend = chart.getOrAddLegend();
   //...
   XDDFLegendEntry legendEntry = getOrAddLegendEntry(legend, 4);
   legendEntry.setDelete(true);
...
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement