Skip to content

Export and Import to Excel

Creating dynamic, interactive organization charts is easier than ever thanks to libraries like OrgChart JS. But what if you want to export your org chart data to an Excel file or load it from one? Here's a simple way to do it using OrgChart JS and SheetJS.

What You'll Need

Include these scripts in your HTML:

html
<script src="https://cdn.balkan.app/orgchart.js"></script>
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

And set up your page:

html
<div id="tree"></div>
<div id="controls">
    <input type="file" id="excelFile" accept=".xlsx, .xls">
    <button onclick="saveDataToExcel()">Save to Excel</button>
</div>

Add the CSS to style the layout:

css
html, body { 
  margin: 0; 
  padding: 0; 
  width: 100%;
   height: 100%; 
   overflow: hidden; 
   font-family: Helvetica; 
}
#tree { 
  width: 100%; 
  height: 90%; 
}
#controls {
  padding: 10px; 
  text-align: center; 
  height: 10%;
}

Initializing the Org Chart

We start by initializing the chart with some sample data:

js
let chart = new OrgChart(document.getElementById("tree"), {
    nodeBinding: {
        field_0: "name",
        field_1: "title"
    }
});

chart.load([
    { id: 1, name: "Amber McKenzie" },
    { id: 2, pid: 1, name: "Ava Field" },
    { id: 3, pid: 1, name: "Peter Stevens" }
]);

Importing Org Chart Data from Excel

Users can upload an Excel file, which is then read and converted into chart data:

js
document.getElementById('excelFile').addEventListener('change', function (event) {
    const file = event.target.files[0];
    readExcelData(file);
});

function readExcelData(file) {
    const reader = new FileReader();

    reader.onload = function (e) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);

        chart.load(jsonData);
    };

    reader.readAsArrayBuffer(file);
}

Exporting Org Chart to Excel

To export the chart data to an Excel file, simply call:

js
function saveDataToExcel() {
    const data = chart.config.nodes;
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'OrgChartData');
    XLSX.writeFile(workbook, 'orgchart.xlsx');
}

Final Thoughts

This setup allows you to easily save and load your org chart data in Excel format, perfect for backups, editing outside the browser, or sharing with colleagues. With just a few lines of code, your org chart becomes even more powerful and user-friendly.