How to get text file content from web and tabulate it - javascript

I need to get a text file from server and display its contents in a table.Tried this code couldnt figure out whats wrong...........................................................................................................................................................................................................
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
margin: auto;
empty-cells: hide;
}
table th
{
background-color: AQUA;
color: #333;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
border-color: #ccc;
}
tr:hover {background-color: #f5f5f5;}
</style>
</head>
<body>
<div align = center>
<input type="text" id="filter" placeholder="Search" title="Type a name" >
</div>
<div id="demo" align = center>
</div>
<script>
window.onload = function() {
var demo = document.getElementById("demo");
if(window.XMLHttpRequest){
var xhttp = new XMLHttpRequest();
}
else{
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.status == 0) {
var responseText= xhttp.responseText;
console.log(this.responseText);
document.getElementById("filter").onkeyup = filterRows;
var ROW_DELIMITER = "\n",
CELL_DELIMITER = " ";
var tableObj = {
headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user",
"Hierarchy code", "Type"],
rows: []
};
}
function convert(responseText) {
tableObj.rows = convertToArray(responseText)
buildTable(tableObj.headers, tableObj.rows);
};
function convertToArray(text) {
return text.split(ROW_DELIMITER).map(function(row) {
return row.split(CELL_DELIMITER);
});
}
function filterRows() {
var input = this;
var rows = tableObj.rows.filter(function(row) {
var matches = row.filter(function(cell) {
return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
});
return matches.length > 0;
});
buildTable(tableObj.headers, rows);
}
function sortRows() {
var th = this;
var index = th.dataset.index;
tableObj.rows.sort(function(rowA, rowB) {
var textA = rowA[index].toUpperCase(),
textB = rowB[index].toUpperCase();
if (textA < textB) {
return -1;
}
if (textA > textB) {
return 1;
}
return 0;
});
buildTable(tableObj.headers, tableObj.rows);
}
function buildTable(headers, rows) {
var table = document.createElement('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < headers.length; i++) {
th = document.createElement('th');
tr.appendChild(th);
th.innerHTML = headers[i];
th.onclick = sortRows;
th.dataset.index = i;
}
for (var j = 0; j < rows.length; j++) {
tr = document.createElement('tr');
table.appendChild(tr);
for (var k = 0; k < rows[j].length; k++) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = rows[j][k];
td.dataset.index = k;
}
}
demo.innerHTML = '';
demo.appendChild(table);
}
convert(responseText);
xhttp.open("GET", "https://www.w3.org/TR/PNG/iso_8859-1.txt", true);
xhttp.send(null);
};
</script>
</body>
</html>

Related

make a button to download a table in format pdf lanscape

Hi friends, I want to help a group to make the table without using the pen and paper. I created the dynamic timetable with javascript, html and css. There is one thing that I found difficult, it is to make a button that allows to download the table in a pdf format in lanscape, which I found difficult, please help me!
here is the link of the code in github : https://github.com/zahiraaa/timetable
const timetable = document.getElementById("timetable");
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const hours = ["7H", "13H", "20H"];
// Create table headers for days
const daysHeaderRow = document.createElement("tr");
const daysHeaderCell = document.createElement("th");
daysHeaderCell.innerHTML = "Days";
daysHeaderRow.appendChild(daysHeaderCell);
days.forEach(day => {
const dayHeaderCell = document.createElement("th");
dayHeaderCell.innerHTML = day;
dayHeaderCell.colSpan = 3;
daysHeaderRow.appendChild(dayHeaderCell);
});
timetable.appendChild(daysHeaderRow);
// Create table headers for hours
const hoursHeaderRow = document.createElement("tr");
const hoursHeaderCell = document.createElement("th");
hoursHeaderCell.innerHTML = "Hours";
hoursHeaderRow.appendChild(hoursHeaderCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const hourHeaderCell = document.createElement("th");
hourHeaderCell.innerHTML = hours[j];
hoursHeaderRow.appendChild(hourHeaderCell);
}
}
timetable.appendChild(hoursHeaderRow);
// Create row for Mina
const names = ["Khalfi","Redouani", "Daki", "Hamma", "Saadane", "Boughanem", "El Ansari","Badilou","Raoui", "Chouiba", "Dahmane", "Achdad", "Bouryal", "Ettouri", "Saadouni"];
for (let name of names) {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.innerHTML = name;
row.appendChild(nameCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const cell = document.createElement("td");
const select = document.createElement("select");
select.classList.add("cell");
const options = [" ", "CP", "ME", "CL", "CE", "R"];
options.forEach(option => {
const optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
select.appendChild(optionElement);
});
cell.appendChild(select);
row.appendChild(cell);
}
}
timetable.appendChild(row);
}
function exportCSV() {
var rows = document.querySelectorAll("#timetable tr");
var csvData = [];
for (var i = 0; i < rows.length; i++) {
var rowData = [];
var cells = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cells.length; j++) {
const select = cells[j].querySelector("select");
if(select){
rowData.push(select.value);
}else{
rowData.push(cells[j].innerText);
}
}
csvData.push(rowData);
}
var csv = Papa.unparse(csvData);
var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, 'timetable.csv');
} else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'timetable.csv');
tempLink.click();
// Convert the CSV data to a PDF and download it
var pdf = new jsPDF('l','mm','a4');
pdf.addPage();
pdf.text(csv, 10, 10);
pdf.save('timetable.pdf');
}
#timetable th {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
background-color: #006699; /* bleu foncé /
}
#timetable tr:nth-child(even) {
background-color: #E6E6FA; / lavande */
}
/* Mise en page globale */
body {
background-color: #f1f1f1;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
/* Style de la barre de navigation */
nav {
background-color: #333;
color: #fff;
display: flex;
justify-content: space-between;
padding: 10px 20px;
}
nav a {
color: #fff;
text-decoration: none;
margin-right: 10px;
}
/* Style de la section principale */
main {
padding: 20px;
}
/* Style des titres */
h1, h2, h3 {
color: #333;
text-align: center;
margin-bottom: 20px;
}
/* Style des paragraphes */
p {
line-height: 1.5;
margin-bottom: 20px;
}
/* Style des images */
img {
max-width: 100%;
}
<table id="timetable">
<body>
<tr>
<td>
<link href="table.css" rel="stylesheet">
<script src="table.js"></script>
<form action="table.php" method="post">
</td>
<tr>
<button onclick="exportCSV()">Export CSV</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<button onclick="exportPDF()">Export PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/pdfmake.min.vfs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/vfs_fonts.js"></script>
<button id="download-pdf-button">Télécharger en PDF</button>
<script>
var downloadButton = document.getElementById("download-pdf-button");
downloadButton.addEventListener("click", downloadPDFWithPDFMake);
</script>
</body>
Nice idea
The csv heading would perhaps be better as Days,,Monday,,,Tuesday,,,Wednesday,,,Thursday,,,Friday,,,Saturday,,,Sunday, since csv does not carry merged fields.
It works well printed landscape by browser but for jsPDF you need to apply it again at the time of add page
pdf.addPage();
defaults to a4,p so
pdf.addPage('a4','l');
should work.
For custom shapes and full syntax visibility use
pdf.addPage([841.89, 595.28],"landscape");

How to overwrite data in a table?

Trying to create a table with data-attributes when clicking on a link
The problem is most likely in this code
I can not understand how to rewrite the data in the table.
Now the data is sequentially added to the table.
My code - https://jsfiddle.net/347x8bwq/
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
Desired behavior - when clicking on a link each time - a new table was created
Before you append your tableRow to the blockTable, clear its innerHTML.
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
blockTable.innerHTML = "";
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
})();
.table {
width: 100%;
table-layout: fixed;
}
td {
border: 1px solid #ccc;
}
.link {
display: block;
margin-bottom: 5px;
}
.block {
padding: 25px;
border: 1px solid #000;
}
Link 1
Link 2
Link 3
<div class="block">
<table class="table">
<tr>
<td>Атрибут1</td>
<td>Title</td>
</tr>
<tr>
<td>Атрибут2</td>
<td>Subtitle</td>
</tr>
<tr>
<td>Атрибут3</td>
<td>1234</td>
</tr>
</table>
</div>
See - https://jsfiddle.net/2wvm6de8/
You have to clear the table before adding a new elements. Just add blockTable.innerHTML = ''; after e.preventDefault();
https://jsfiddle.net/vLm60kzq/

how to find the minimum value of each row and column from given table

i want to find the minimum value of each row also minimum value of each column
add input to each row and column produced after the table generation
want to find minimum value of each row and minimum value of each column
also minimum value of whole table
i want to input the user values instead of default value cell in fiddle given below
[fiddle][1]
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row;
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
row = generateRow(nOfColumns);
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text;
for (var i = 0; i < n; i++) {
text = document.createTextNode(Math.trunc(100 * Math.random()));
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
ul {
margin-left: 0;
padding-left: 0;
width: 200px;
}
ul li {
list-style: none;
padding-bottom: 1em;
}
input[type=number] {
width: 70px;
float: right;
}
table, td {
border: 1px solid #000;
padding: 5px;
border-spacing: 0;
border-collapse: collapse;
caption-side: bottom;
}
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" validate />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="btnCopy" />
</li>
</ul>
<div id="wrap"></div>
please give me suggestion about it
also i want to store the minimum value of each row and column.
Check this
const generate = document.getElementById('generate');
function handleTable(cont) {
const table = cont.getElementsByTagName('table')[0],
cells = table.getElementsByClassName('cell'),
all_cells = table.getElementsByTagName('td'),
size = cells.length;
let currentValue, minimum;
const p = document.createElement('p'),
text = document.createTextNode('Minimum is: '),
minValue = document.createElement('span');
p.appendChild(text);
p.appendChild(minValue);
cont.appendChild(p);
const rowsNum = table.getElementsByTagName('tr').length,
colsNum = table.getElementsByTagName('td').length/(rowsNum);
const addInput = function(e){
currentValue = e.target.innerHTML;
e.target.innerHTML = '';
let myInput = document.createElement('input');
myInput.classList.add('my_input');
e.target.appendChild(myInput).focus();
}
const getMinimum = function(){
let cur_rows = [],
temp2 = rowsNum-1;
while(temp2--)
cur_rows.push([]);
let cur_cols = [],
temp1 = colsNum-1;
while(temp1--)
cur_cols.push([]);
let values = [];
for (let i = 0; i < size; i++){
let item = cells[i].innerHTML;
if(item){
values.push(item);
let cur_x = i % (colsNum-1),
cur_y = (i - cur_x) / (colsNum-1);
cur_cols[cur_x].push(item);
cur_rows[cur_y].push(item);
}
}
let cur_min = Math.min.apply(null, values);
minValue.innerHTML = ((cur_min && (cur_min != Infinity)) || (cur_min == 0)) ? cur_min : '';
let cur_min_rows = [];
for (let i = 0; i<cur_rows.length; i++)
cur_min_rows[i] = Math.min.apply(null, cur_rows[i]);
let cur_min_cols = [];
for (let i = 0; i < cur_cols.length; i++)
cur_min_cols[i] = Math.min.apply(null, cur_cols[i]);
for (let i = 0; i < all_cells.length; i++)
if (all_cells[i].classList.contains('result')){
let cur_x = i % colsNum,
cur_y = (i - cur_x)/(colsNum);
all_cells[i].innerHTML = '';
if ((cur_x == colsNum-1) && (cur_min_rows[cur_y] != Infinity))
all_cells[i].innerHTML = cur_min_rows[cur_y];
if ((cur_y == rowsNum-1) && (cur_min_cols[cur_x] != Infinity))
all_cells[i].innerHTML = cur_min_cols[cur_x];
}
}
const removeInput = function(e){
let elem = e.target;
if (!elem.classList.contains('my_input')) {
for (let i = size; i--;){
let input = cells[i].getElementsByClassName('my_input')[0];
if(input) {
let value = input.value;
cells[i].removeChild(input);
if(value){
value = value.replace(/ /g,'');
cells[i].innerHTML = value;
getMinimum();
}
else {
cells[i].innerHTML = currentValue;
currentValue = '';
}
}
}
}
}
for (let i = size; i--;)
cells[i].addEventListener('click', addInput);
document.body.addEventListener('click', removeInput, true);
};
const generateRow = function(cols, isLast){
let row = document.createElement('tr');
const className = (isLast) ? 'result' : 'cell';
for (let i = cols; i--;) {
let cell = document.createElement('td');
cell.classList.add(className);
row.appendChild(cell);
}
let cell = document.createElement('td');
cell.classList.add('result');
row.appendChild(cell);
if(isLast)
cell.classList.remove('result');
return row;
}
const generateTable = function(e){
const wrap = document.getElementById('wrap'),
rows = document.getElementById('rows'),
columns = document.getElementById('columns'),
newTable = document.createElement('table');
let row;
for (let i = 0; i <= rows.value; i++ ){
if(i == rows.value)
row = generateRow(columns.value, true);
else
row = generateRow(columns.value, false);
newTable.appendChild(row);
}
if (wrap.hasChildNodes())
wrap.innerHTML = '';
wrap.appendChild(newTable);
handleTable(wrap);
};
generate.addEventListener('click', generateTable);
.result, .cell{
width:30px;
height: 30px;
text-align:center;
}
.cell {
border:1px solid;
}
table {
border-collapse: collapse;
}
.my_input {
width: 25px;
text-align:center;
border:none;
outline:none;
}
ul {
width: 200px;
}
ul li {
list-style: none;
margin-bottom: 12px;
}
input[type=number] {
width: 70px;
float: right;
}
<form>
<ul>
<li>
<label>Rows</label>
<input type="number" id="rows" value="">
</li>
<li>
<label>Columns</label>
<input type="number" id="columns" value="">
</li>
<li>
<input type="button" value="Generate" id="generate">
</li>
</ul>
</form>
<div id="wrap"></div>

How to change child classes by changing only the parent class?

I have a table with black and white cells and I want to create a button which changes the colors of cells.
I have done it by using for loop jsfiddle.net
Now, I dont want to use the function below. Is it possible to change only the class atribute of whole table to change class of all td tag's?
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
Yes it's possible you just need a css class for the table to do it and a function to toggle this class with your table.
This is how should be your css defined:
.myTable td{
background: gray;
}
And this is the JS function to toggle it in the table:
function toggleClass(){
var table = document.querySelector("table");
if(table.className !== "myTable"){
table.className = "myTable";
}else{
table.className = '';
}
}
Demo:
This is an updated Demo:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
}
tableCreate(5);
function toggleClass() {
var table = document.querySelector("table");
if (table.className !== "myTable") {
table.className = "myTable";
} else {
table.className = '';
}
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.myTable td {
background: gray;
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
<input type="button" value="Change table" onclick="toggleClass()">
</body>
Instead of using the for loop, try toggling the invert class name on the table element. Then adjust the css accordingly, as in the snippet below:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
tbl.setAttribute('id', 'myTable');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var table = document.getElementById('myTable');
table.classList.toggle('invert')
}
tableCreate(5);
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.invert .t {
background: black
}
.invert .t2 {
background: white
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
</body>
If you're looking to just change the colors of the cells, you could toggle the class of the table and then use CSS selectors on the cells like the following:
.table-dark td { background-color: #000; }
.table-light td { background-color: #fff; }

improve csv file reader by removing quotes from fields, supporting a header, and allowing other seperators

I would like my file to not have quotations when displayed in html. Meaning there are quotes by every word. I would like to take that away.
And I would also like to add a th tag so I can have a header.
And I don't wanna just have comma separated, I also wanna have other separators such as |
Here is my code:
css:
table
{
border: 1px solid #ccc;
}
table th
{
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border-color: #ccc;
}
Javascript:
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
HTML:
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
So I took a look at your code and made a jsfiddle off of it.
Heres the full fiddle
$(function() {
$("#upload").bind("click", function() {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof(FileReader) != "undefined") {
var reader = new FileReader(),
table = $("<table>"),
separator = ',',
rows,
rowLength;
reader.onload = function(e) {
rows = e.target.result.split(/[\r\n|\n]+/);
rowLength = rows.length;
for (var i = 0; i < rowLength; i++) {
var row = $("<tr>"),
cells = rows[i].split(separator),
cellLength = cells.length,
cell;
for (var j = 0; j < cellLength; j++) {
// Special case for the first row
cell = (i === 0) ? $("<th>") : $("<td>");
cell.html(cells[j]);
row.append(cell);
}
// Special case for first row (thead)
if (i === 0) {
row = $('<thead>').html(row);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
a {
display: block;
}
table {
border: 1px solid #ccc;
}
table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th,
table td {
padding: 5px;
border-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Dummy CSV
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
I made slight adaptations to it. It turns out (at least from the dummy csv I am using), that no quotes are being added...
The split-by-rows regex was not seeming to work, so I changed it to:
var rows = e.target.result.split(/[\r\n|\n]+/);
In the comments you wanted to add thead and th support. To do that, I just added a conditional on the two lines:
cell = (i === 0) ? $("<th>") : $("<td>");
if (i === 0) {
row = $('<thead>').html(row);
}
You mentioned wanting to separate on things other than a comma. As you already know, you are dealing with "Comma-Separated-Values", so separating by comma is expected... but to make your code more generic, I added the separator in a variable instead (so you can swap that out with what you expect the separator to be):
var separator = ',';
var cells = rows[i].split(separator);
Hope that helped! :)
$(function() {
$("#upload").bind("click", function() {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof(FileReader) != "undefined") {
var reader = new FileReader(),
table = $("<table>"),
separator = ',',
rows,
rowLength;
reader.onload = function(e) {
rows = e.target.result.split(/[\r\n|\n]+/);
rowLength = rows.length;
for (var i = 0; i < rowLength; i++) {
var row = $("<tr>"),
cells = rows[i].split(separator),
cellLength = cells.length,
cell;
for (var j = 0; j < cellLength; j++) {
// Special case for the first row
cell = (i === 0) ? $("<th>") : $("<td>");
cell.html(cells[j]);
row.append(cell);
}
// Special case for first row (thead)
if (i === 0) {
row = $('<thead>').html(row);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
a {
display: block;
}
table {
border: 1px solid #ccc;
}
table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th,
table td {
padding: 5px;
border-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Dummy CSV
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>

Categories

Resources