Skip to content
  1. Examples

Excel Advanced

This example shows how to export the graph data as an Excel file. It uses the Excel export API, and creates one tab per graph element type.

ts
import Ogma from '@linkurious/ogma';

const randomGraph = async (ogma: Ogma, N: number, E: number) => {
  const g = await ogma.generate.random({ nodes: N, edges: E });

  for (let i = 0; i < N; i++) {
    const node = g.nodes[i];
    node.attributes = {
      x: Math.random() * 100,
      y: Math.random() * 100,
      text: {
        minVisibleSize: 0,
        content: 'Node ' + i,
        backgroundColor: '#0094ff',
        color: '#fff'
      },
      radius: 3 + Math.random() * 3,
      color: '#0094ff'
    };
    node.data = {
      properties: {
        aString: 'abc ' + i,
        aProblematicString: 'cr"p\n\r ',
        aFormulaInjectionString: "%0A-3+3+cmd|' /C calc'!D2",
        aBoolean: true,
        anInteger: i,
        aFloat: Math.random(),
        anArray: [1, 2, 3],
        aNull: null,
        anUndef: undefined,
        anObject: {},
        aFunction: () => {}
      },
      category: i % 2 ? 'catA' : 'catB'
    };
  }

  for (let i = 0; i < E; i++) {
    const edge = g.edges[i];
    edge.attributes = {
      text: 'Edge ' + i,
      width: 1 + Math.random(),
      color: '#0094ff'
    };
    edge.data = {
      aString: 'abc ' + i,
      aBoolean: true,
      anInteger: i,
      aNull: null,
      anObject: {},
      aFunction: () => {},
      category: i % 2 ? 'catC' : 'catD'
    };
  }

  return g;
};

const ogma = new Ogma({
  container: 'graph-container'
});

const graph = await randomGraph(ogma, 10, 10);
await ogma.setGraph(graph);
await ogma.layouts.force({ locate: true, duration: 0 });

await ogma.export.xlsx({
  filename: 'my-graph.xlsx',
  tab: {
    nodes: node => node.getData('category'),
    edges: edge => edge.getData('category')
  },
  nodeData: (data, allTabs) => {
    if (allTabs[0] === 'catA') {
      return {
        // you can rename column names in here
        counter: data.properties.aString,
        active: data.properties.aBoolean,
        related: data.properties.anArray
      };
    }
    if (allTabs[0] === 'catB') {
      return {
        integer: data.properties.anInteger,
        float: data.properties.aFloat
      };
    }
    return {}; // empty
  }
  // edgeData is used as default: the full data object will be printed for catC and catD tabs
});
html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.11.12/dist/xlsx.core.min.js"></script>

    <link type="text/css" rel="stylesheet" href="styles.css" />
  </head>

  <body>
    <div id="graph-container"></div>
    <script src="index.ts" type="module"></script>
  </body>
</html>
css
#graph-container {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
  margin: 0;
  overflow: hidden;
}