I want to create a button to load an xls or csv file and make this Excel table into an HTML table, how can I do this using JavaScript? Please ...
I want to create a button to load an xls or csv file and make this Excel table into an HTML table, how can I do this using JavaScript? Please ...
There is a jQuery plugin that enables the conversion of .csv files to JSON. This way you can extract the data from the file and work with it on screen as you wish.
Follow the link from the official plugin site: papaparse.com
I made this code below to test the plugin (You can easily copy and test on your computer):
<html>
<head>
<title>Teste PapaParse</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script><scriptsrc="http://papaparse.com/resources/js/papaparse.js"></script>
<style>
td {
border: 1px solid #ccc;
padding: 1px;
text-align: center;
font-family: Helvetica, sans-serif;
}
table {
border-collapse: collapse;
margin:auto;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#btnConverter').click(function(){
// veja mais em: http://papaparse.com/docs#jquery
$('input[type=file]').parse({
//definindo configuração
config : buildConfig()
});
});
function buildConfig()
{
// função chamada quando completar a conversão
return {complete: Complete};
}
function Complete(results)
{
// limpando conteudo da div
$('#tabela_aqui').html('');
// inserindo tabela na div
$('<table id="tabela"></table>').appendTo('#tabela_aqui');
// inserindo linhas
for (var i = 0; i < results.data.length; i++) {
$('<tr></tr>').appendTo('#tabela');
}
// inserindo celulas nas linhas
$('tr').each(function(key, val) {
for (var j = 0; j < results.data[0].length; j++) {
$(this).append('<td>'+results.data[key][j]+'</td>');
}
});
}
});
</script>
</head>
<body>
Arquivo (.csv) <input type="file" name="csv_file"><br>
<button id="btnConverter">Converter</button>
<br/>
<div id="tabela_aqui"></div>
</body></html>
The above code provides a button to select the file and another one that converts the file to JSON and displays it as a table.
In this link there is a .csv file to test functionality.