Simple Google Sheet Custom Component

I thought I’d see if ChatGPT could whip up some code to display some Google Sheet data using a Custom Component in Elements… it did a great job!

Here’s the code… you just need to paste it into a custom component and replace my sheet ID with the sheet ID you want to use (remeber to make it public). Obviously if you have more than three columns you’ll need to adjust the code. Have fun!

<div class="container mx-auto p-6">
    <h2 class="text-2xl font-bold mb-4">Google Sheets Data</h2>
    <div class="overflow-x-auto">
        <table class="min-w-full bg-white border border-gray-200 shadow-md rounded-lg">
            <thead>
                <tr class="bg-gray-100 text-gray-700">
                    <th class="px-4 py-2 border">Name</th>
                    <th class="px-4 py-2 border">Email</th>
                    <th class="px-4 py-2 border">Role</th>
                </tr>
            </thead>
            <tbody id="sheet-data"></tbody>
        </table>
    </div>
</div>

<script>
    async function fetchData() {
        const sheetID = "13aTre5QDB1US0aC24WxtvAeSyfUExqDo410nKo4CUGs"; // Replace with your Sheet ID
        const url = `https://docs.google.com/spreadsheets/d/${sheetID}/gviz/tq?tqx=out:json`;

        try {
            const response = await fetch(url);
            const text = await response.text();
            const json = JSON.parse(text.substr(47).slice(0, -2)); // Remove Google’s padding

            const rows = json.table.rows;
            const tableBody = document.getElementById("sheet-data");
            tableBody.innerHTML = ""; // Clear existing rows

            rows.forEach(row => {
                const name = row.c[0]?.v || "N/A";  // Column 1 (Name)
                const email = row.c[1]?.v || "N/A"; // Column 2 (Email)
                const role = row.c[2]?.v || "N/A";  // Column 3 (Role)

                tableBody.innerHTML += `
                    <tr class="border-b hover:bg-gray-50">
                        <td class="px-4 py-2 border">${name}</td>
                        <td class="px-4 py-2 border">${email}</td>
                        <td class="px-4 py-2 border">${role}</td>
                    </tr>
                `;
            });
        } catch (error) {
            console.error("Error fetching Google Sheets data:", error);
        }
    }

    fetchData();
</script>
2 Likes

I’m working on a set of Google Sheet components with a lot of options…
This is just the an example of what’s possible:

1 Like

That is looking great, I think A LOT of users will find this very useful!