Home > AI > Frontend > Electron >

Use Electron to show data from local excel

index.js

const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const path = require("path");
const fs = require("fs");
const XLSX = require("xlsx");

function createWindow() {
  const win = new BrowserWindow({
    width: 1000,
    height: 700,
    webPreferences: {
      preload: path.join(__dirname, "renderer.js"),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  win.loadFile("index.html");
}

app.whenReady().then(createWindow);

ipcMain.handle("open-excel-file", async () => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    filters: [{ name: "Excel", extensions: ["xlsx", "xls"] }],
    properties: ["openFile"]
  });

  if (canceled || !filePaths[0]) return null;

  const fileBuffer = fs.readFileSync(filePaths[0]);
  const workbook = XLSX.read(fileBuffer, { type: "buffer" });
  const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
  const data = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });

  return data;
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Excel Chart Viewer</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    #chart-container { width: 800px; height: 500px; }
  </style>
</head>
<body>
  <h2>&#x1f4ca; Excel to Chart</h2>
  <button onclick="loadExcel()">Open Excel File</button>
  <div id="chart-container">
    <canvas id="myChart"></canvas>
  </div>

  <script>
    async function loadExcel() {
      const data = await window.excelAPI.openFile();
      if (!data || data.length < 2) return alert("No data loaded!");

      const labels = data.slice(1).map(row => row[0]); // e.g. names
      const values = data.slice(1).map(row => row[1]); // e.g. numbers

      new Chart(document.getElementById("myChart"), {
        type: "bar",
        data: {
          labels: labels,
          datasets: [{
            label: data[0][1],
            data: values,
            backgroundColor: "#42a5f5"
          }]
        }
      });
    }
  </script>
</body>
</html>

renderer.js

const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("excelAPI", {
  openFile: () => ipcRenderer.invoke("open-excel-file")
});

package.json

{
  "name": "my-electron-app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "electron": "^35.1.4"
  },
  "dependencies": {
    "xlsx": "^0.18.5"
  }
}

Leave a Reply