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...
3 answers
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.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.
GITHUB: ngJsonExportExcel
Transferência Directa Da Biblioteca: Transferência
Protector de Ficheiros JS: transferência
Como usar?
- inclua o módulo no seu aplicativo
Var myapp = angular.módulo ("myapp", ["ngJsonExportExcel"])
- adicione um botão de exportação e use a Directiva
ng-json-export-excel
e 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>