JavaScript JSON para obter ficheiros do Excel

Tenho dados Json e preciso converter dados json para arquivo Excel usando javascript,

URL de Referência : http://jsfiddle.net/hybrid13i/JXrwM/

estou a usar este código:

function JSONToTSVConvertor(JSONData, ReportTitle, ShowLabel, myTemplateName){

    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var TSV = '';    
    //Set Report title in first row or line
    //TSV += ReportTitle + '\r\n\n';
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";
        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {
            //Now convert each value to string and tab-seprated
            row += index + '    ';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        TSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string tab-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '" ';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        TSV += row + '\r\n';
    }

    if (TSV == '') {        
        alert("Invalid data");
        return;
    }   
    var blob = new Blob([TSV], {type: "data:text/tsv;charset=utf-8"});
    //Generate a file name

    var fileName = myTemplateName;
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName += ReportTitle.replace(/ /g,"_"); 
    saveAs(blob, ""+fileName+".tsv");
}

este código de amostra funciona no formato csv e tsv. e preciso de me destacar no formato, acho que não faço ideia, por favor, ajuda-me. o pls sugere um código de exemplo. Obrigado...

Author: Elango, 2015-03-06

3 answers

[[2] CSV, como disse, é o próprio arquivo excel. Mas, em muitos locais, csv gerado pelo script acima é aberto incorretamente, onde o excel coloca tudo em uma célula. Uma pequena modificação do script original ajuda: apenas substituir o cabeçalho com " sep=,".
var CSV = 'sep=,' + '\r\n\n';

Trabalhando como exemplo com a mudança aqui: https://jsfiddle.net/1ecj1rtz/.

Passei algum tempo a descobrir isto e, por isso, a responder ao velho tópico para ajudar os outros a poupar tempo.
 6
Author: Dmitry, 2015-04-16 08:15:05

O Excel é um formato muito complexo com muitas versões. Se você realmente precisa fazer isso eu iria investigar algumas das bibliotecas JavaScript que outros escreveram. Faça uma pesquisa no Google para "javascript excel writer" para ver alguns exemplos.

 1
Author: Eamonn O'Brien-Strain, 2015-03-06 07:06:56
Sei que é um pouco tarde para responder, mas encontrei uma bela biblioteca que faz todo o trabalho duro que faz.

GITHUB: ngJsonExportExcel

Transferência Directa Da Biblioteca: Transferência

Protector de Ficheiros JS: transferência

Como usar?

  1. inclua o módulo no seu aplicativo

Var myapp = angular.módulo ("myapp", ["ngJsonExportExcel"])

  1. adicione um botão de exportação e use a Directiva ng-json-export-excele transferir dados para a Directiva

Ng-json-export-excel: é o nome da Directiva

Dados: são os dados que serão exportados (JSON)

Report-fields:

Passa o nome da coluna e as chaves que estão presentes no teu JSON e.g. nome do Cliente":"Nome do cliente"

HTML

<button ng-json-export-excel data="dataList" report-fields="{'uesr.username': 'Heder 1', keyjson2: 'Header 2', keyjson3: 'Head 3'}" filename =" 'export-excel' " separator="," class="css-class"></button>
 0
Author: Vikas Bansal, 2017-08-06 08:24:55