Creacion de un csv desde tabla html con js
Html
<div class="container-fluid table-responsive">
<table class="table table-hover" id="dataTable">
<thead class="thead-dark text-center">
<thead class="thead-dark text-center">
<th hidden="true">#</th>
<th>Año</th>
<th>No. Empleado</th>
<th>Nombre</th>
<th>RFC</th>
<th>Oficio</th>
<th>Area</th>
<th>Resultado</th>
<th>Dirigido</th>
</thead>
</thead>
<tbody class="text-center" id="datos_cargar"></tbody>
</table>
</div>
<button id="exportar_csv" type="button" class="button">Export to CSV</button>
<script src="./public/js/busqueda_masiva.js"></script>
Js
busqueda = () => {
document.querySelector('#plantilla_busqueda').addEventListener('click', plan
tilla);
document.querySelector('#carga_csv').addEventListener('submit', buscar_datos
);
document.querySelector('#exportar_csv').addEventListener('click', csv);
}
csv = () => {
const dataTable = document.getElementById("dataTable");
const exporter = new TableCSVExporter(dataTable);
const csvOutput = exporter.convertToCSV();
const csvBlob = new Blob([csvOutput], { type: "text/csv" });
const blobUrl = URL.createObjectURL(csvBlob);
const anchorElement = document.createElement("a");
anchorElement.href = blobUrl;
anchorElement.download = "table-export.csv";
anchorElement.click();
setTimeout(() => {
URL.revokeObjectURL(blobUrl);
}, 500);
}
class TableCSVExporter {
constructor(table, includeHeaders = true) {
this.table = table;
this.rows = Array.from(table.querySelectorAll("tr"));
if (!includeHeaders && this.rows[0].querySelectorAll("th").length) {
this.rows.shift();
}
}
convertToCSV() {
const lines = [];
const numCols = this._findLongestRowLength();
for (const row of this.rows) {
let line = "";
for (let i = 0; i < numCols; i++) {
if (row.children[i] !== undefined) {
line += TableCSVExporter.parseCell(row.children[i]);
}
line += (i !== (numCols - 1)) ? "," : "";
}
lines.push(line);
}
return lines.join("\n");
}
_findLongestRowLength() {
return this.rows.reduce((l, row) => row.childElementCount > l ? row.chil
dElementCount : l, 0);
}
static parseCell(tableCell) {
let parsedValue = tableCell.textContent;
// Replace all double quotes with two double quotes
parsedValue = parsedValue.replace(/"/g, `""`);
// If value contains comma, new-line or double-quote, enclose in double
quotes
parsedValue = /[",\n]/.test(parsedValue) ? `"${parsedValue}"` : parsedVa
lue;
return parsedValue;
}
}