Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

array to excel javascript

//my solution was export as csv and opn file directly in excel
//here is how i didit its in spanish sorry nut you can always google translate

https://asfo.medium.com/exportando-un-json-a-csv-con-javascript-410aee9381d8


function convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

			if (array[i][index] != null){
				line += array[i][index];
			} else {
				line += ''
			}
        }

        str += line + '
';
    }

    return str;
}

function exportCSVFile(headers, items, fileName) {
 if (headers) {
  items.unshift(headers);
 }

const jsonObject = JSON.stringify(items);

const csv = convertToCSV(jsonObject);

const exportName = fileName + ".csv" || "export.csv";

const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
 if (navigator.msSaveBlob) {
  navigator.msSaveBlob(blob, exportName);
 } else {
  const link = document.createElement("a");
  if (link.download !== undefined) {
   const url = URL.createObjectURL(blob);
   link.setAttribute("href", url);
   link.setAttribute("download", exportName);
   link.style.visibility = "hidden";
   document.body.appendChild(link);
   link.click();
   document.body.removeChild(link);
  }
 }
}


const headers = {
 id: 'Identificador',
 nombre: 'Nombre'
};

const data = [
 { id: 1, nombre: 'John Doe' },
 { id: 2, nombre: 'Juan' },
 { id: 3, nombre: 'Samanta' }
];

exportCSVFile(headers, data, 'nombres');

 
PREVIOUS NEXT
Tagged: #array #excel #javascript
ADD COMMENT
Topic
Name
1+9 =