Hello, I am trying out your Elements program and I have a specific stack that I use called table CSV. It’s where I take a spreadsheet and insert it into a stack and I get a table on my websites. I have one particular website that uses a lot of spreadsheets. I’m just wondering if you have a table CSV for Elements.
We don’t currently have a built in CSV component in Elements.
Could you send a link to the stack you’re using, and a link to a live URL using the stack, and we can see how you might be able to achieve the same thing in Elements
In Pages
add a file table.csv
Name,Age,Type
Ulrich,59,Human
Banu,8,Grandma Dog
Asta,4,Mother Dog
Herr Blau, 28 Days,Baby Dog
add a HTML element
Template:
<csv-table src="/table.csv"></csv-table>
Styles:
table {
width: 100%;
border-collapse: collapse;
font-size: 1rem;
}
th, td {
padding: 0.5em;
border: 1px solid #bbb;
}
th {
background: #f5f5f5;
}
Javascript:
class CsvTable extends HTMLElement {
static get observedAttributes() { return ['src']; }
connectedCallback() {
// Prüfen, ob das Template schon eingefügt wurde
if (!this.querySelector('table')) {
this.innerHTML = `
<table>
<thead></thead>
<tbody></tbody>
</table>
`;
}
const src = this.getAttribute('src');
if (src) this.loadCsv(src);
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'src' && newValue && newValue !== oldValue) {
this.loadCsv(newValue);
}
}
async loadCsv(url) {
try {
const response = await fetch(url);
if (!response.ok) {
this.renderError('Fehler beim Laden der CSV-Datei.');
return;
}
const text = await response.text();
const rows = this.parseCsv(text);
if (rows.length === 0) {
this.renderError('Keine Daten gefunden.');
return;
}
this.renderTable(rows);
} catch (e) {
this.renderError('Fehler beim Laden der CSV-Datei.');
}
}
parseCsv(text) {
return text.trim().split('\n').map(row =>
row.split(',').map(cell => cell.trim())
);
}
renderTable(rows) {
const [header, ...body] = rows;
const thead = this.querySelector('thead');
const tbody = this.querySelector('tbody');
thead.innerHTML = `<tr>${header.map(h => `<th>${h}</th>`).join('')}</tr>`;
tbody.innerHTML = body.map(row =>
`<tr>${row.map(cell => `<td>${cell}</td>`).join('')}</tr>`
).join('');
}
renderError(message) {
const thead = this.querySelector('thead');
const tbody = this.querySelector('tbody');
if (thead && tbody) {
thead.innerHTML = '';
tbody.innerHTML = `<tr><td colspan="100%">${message}</td></tr>`;
}
}
}
customElements.define('csv-table', CsvTable);
You have to export it to a web server. Then it works.
I didn’t know JavaScript could do that. I need to learn more about JavaScript.
1 Like