So I'm writing a simple web app that all it does is load a CSV, add an "agree?" checkbox to the end of each row, then downloads the table as CSV.
That downloaded CSV will later be converted to an SQL table, but before that, I need to find a way to give each row a boolean variable based on what the user checked or didn't check.
So here's the JS which is built out of a few functions that load a CSV, add the checkbox I mentioned, then convert it back.
function buildHeaderElement (header) {
const headerEl = document.createElement('thead')
headerEl.append(buildRowElement(header, true))
return headerEl
}
function buildRowElement (row, header) {
const columns = row.split(',')
const rowEl = document.createElement('tr')
for (column of columns) {
const columnEl = document.createElement(`${header ? 'th' : 'td'}`)
columnEl.textContent = column
rowEl.append(columnEl)
}
rowEl.append(provideeColumnAgree(row, header))
return rowEl
}
function provideeColumnAgree(row, header) {
const columnAgree = document.createElement(`${header ? 'th' : 'td'}`)
if(header)
{
columnAgree.textContent = 'Agree?';
}
else
{
const checkboxAgree = document.createElement(`input`)
checkboxAgree.setAttribute("type", "checkbox");
columnAgree.append(checkboxAgree)
}
return columnAgree
}
function populateTable (tableEl, rows) {
const rowEls = [buildHeaderElement(rows.shift())]
for (const row of rows) {
if (!row) { continue }
rowEls.push(buildRowElement(row))
}
tableEl.innerHTML= ''
return tableEl.append(...rowEls)
}
function createSubmitBtn() {
var button = document.createElement("button");
button.innerHTML = "Download CSV";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
exportTableToCSV('members.csv')
});
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
downloadLink.click();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
function readSingleFile ({ target: { files } }) {
const file = files[0]
const fileReader = new FileReader()
const status = document.getElementById('status')
if (!file) {
status.textContent = 'No file selected.'
return
}
fileReader.onload = function ({ target: { result: contents } }) {
status.textContent = `File loaded: ${file.name}`
const tableEl = document.getElementById('csvOutput')
const lines = contents.split('\n')
populateTable(tableEl, lines)
status.textContent = `Table built from: ${file.name}`
createSubmitBtn()
}
fileReader.readAsText(file)
}
window.addEventListener('DOMContentLoaded', _ => {
document.getElementById('fileSelect').addEventListener('change', readSingleFile)
})
The HTML is quite simple
<html>
<body>
<input type="file" id="fileSelect"/>
<div id="status">Waiting for CSV file.</div>
<table id="csvOutput"></table>
<script src="script.js"></script>
</body>
</html>
Here's the link to the project: https://jsfiddle.net/95tjsom3/1/
While downloading the csv, you can check whether the column contains checkbox or not. And if it has a checkbox, whether it is checked or not. Then you can alter the contents of that particular column.
function exportTableToCSV(filename) {
var checkboxes = document.getElementsByTagName("input"); // get all checkboxes in the array
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++) {
if(cols[j].innerHTML.includes('<input type="checkbox">')) {
if(checkboxes[i].checked) {
row.push("AGREE");
}
else {
row.push("NOT AGREE");
}
}
else {
row.push(cols[j].innerText);
}
}
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
Related
Can we able to update a particular cell in csv file using Javascript?
Can anyone share please share the sample javascript code?
Considering you have a workbook, here is how you may loop through the rows and change the cell value:
var rows = workbook.sheets[0].rows;
for (var ri = 0; ri < rows.length; ri++) {
var row = rows[ri];
for (var ci = 0; ci < row.cells.length; ci++) {
var cell = row.cells[ci];
cell.value = new_data;
cell.hAlign = "left";
}
}
Update
var file = document.getElementById('docpicker')
file.addEventListener('change', importFile);
function importFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = e => {
var contents = processExcel(e.target.result);
console.log(contents)
}
r.readAsBinaryString(f);
} else {
console.log("Failed to load file");
}
}
function processExcel(data) {
var workbook = XLSX.read(data, {
type: 'binary'
});
// inject your logic as per need
var rows = workbook.sheets[0].rows;
for (var ri = 0; ri < rows.length; ri++) {
var row = rows[ri];
for (var ci = 0; ci < row.cells.length; ci++) {
var cell = row.cells[ci];
cell.value = new_data;
cell.hAlign = "left";
}
}
};
I have a legacy barcode scanning application, which is used to issue items from the store. It has a combo box which has a list of all pending orders and when the user selects an order, it will list out the items expected to be issued with their quantities. Then the user presses 'f7' as a shortcut key and a new barcode field is added dynamically and then they have to scan the barcode of the bin location and after it is validated, automatically another field for the item code is added dynamically. After the item code is validated, the quantity field is added dynamically wherein the user inputs the quantity taken from that bin location. The user presses 'f7' again and the process repeats unless they finish collecting the items.
At last, they save the order and proceeds with another order.
The problem which I am facing right now is that the number of times user selects the order and presses 'f7', that number of fields are added automatically.
Example, the first time when the page loads, the user selects the order, presses 'f7', one field for bin location is added automatically, no issue here. Now, due to some reason, the user selects a second order and presses 'f7', now 2 bin location fields are added automatically. The user selects third order and presses 'f7', now 3 bin location fields are added automatically. This goes on repeating unless the user refreshes the page and starts new.
There is a variable serial defined which I have tried resetting at the time of user selecting the order but the problem still exists. I have tried resetting the variable at different places, but the problem doesn't go away.
I have used hotkeys javascript to use 'f7' as the shortcut
https://unpkg.com/hotkeys-js#3.7.1/dist/hotkeys.js
During the HTML load, a select input box is populated with all the pending orders and the below code calls the function ValueChanged with the order number when the value is changed:
<select name="Request" onchange="ValueChanged(this);;">
The function ValueChanged builds a URL with the order number and passes an Ajax request to another page through function SendAjaxRequest which collects the required data and then another function SetValues builds a table with the data on the page. Now, this function SetValues has the shortcut function hotkeys which adds the field dynamically.
Below is the javascript code
stopEvent = function(ffevent)
{
var current_window = window;
if(current_window.event) //window.event is IE, ffevent is FF
{
//IE
current_window.event.cancelBubble = true; //this stops event propagation
current_window.event.returnValue = false; //this prevents default (usually is what we want)
}
else
{
//Firefox
ffevent.stopPropagation();
ffevent.preventDefault();
};
}
function validateAllInputBoxes(ffevent)
{
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; ++i)
if(inputs[i].type === 'text')
if(inputs[i].value === '')
{
alert("form could not be sent one input text field is empty");
stopEvent(ffevent);
}
var x = document.forms["myForm"]["Request"].value;
if (x == null || x == "") {
alert("Select GRN");
stopEvent(ffevent);
}
var inputFormDiv = document.getElementsByTagName('input').length;
if (inputFormDiv<=1) {
alert("Enter atleast one BIN Information");
stopEvent(ffevent);
}
}
function addRow() {
var myName = document.getElementById("name");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
var deleteRow = function (link) {
var row = link.parentNode.parentNode;
var table = row.parentNode;
table.parentNode.removeChild(table);
}
//function deleteRow(obj) {
// var index = obj.parentNode.parentNode.rowIndex;
// var table = document.getElementById("myDynamicTable2");
// table.deleteRow(index);
//}
function addTable() {
}
function load() {
console.log("Page load finished");
}
function GetXmlHTTP() {
//first check for IE:
if (window.ActiveXObject) {
var objXML = 0;
try {
objXML = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex) {
try {
objXML = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(ex) {
alert("AJAX: your browser does not support proper XMLHTTP");
}
}
return objXML;
}
//maybe Mozilla?
if (window.XMLHttpRequest)
return new XMLHttpRequest();
//unknown browser..
alert("AJAX: unknown browser.");
return 0;
} //end function GetXmlHTTP
/*
this function send request to the given URL via
GET method.
*/
function SendAjaxRequest(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
SetValues(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest1(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues1(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest2(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues2(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function ValueChanged(oDDL)
{
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveBIN.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
rqstnumber = selectedValue;
SendAjaxRequest(strURL);
}
}
function ValueChangedDesc(oDDL)
{
var selectedValue = oDDL.value;
selectedValueBIN = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveDesc.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest1(strURL);
}
}
function ValueChangedItem(oDDL)
{
var xperia = document.forms["myForm"]["Request"].value;
//var binival = bini.value;
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveItem.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime() + "&rqn=" + xperia + "&bin=" + selectedValueBIN;
//alert(strURL);
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest2(strURL);
}
}
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(3);
}
function SetValues1(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
var txt = document.activeElement.name;
var numb = txt.match(/\d/g);
numb = numb.join("");
var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table1 = document.createElement('TABLE');
//table1.border='1';
//var tableBody2 = document.createElement('TBODY');
//table1.appendChild(tableBody2);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'ItemCode');
input.setAttribute("id", serial+'ItemCode');
//input.setAttribute("autofocus",'True');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.onkeydown = function(){ValueChangedItem(this);};
var lblt = document.createTextNode('Item Code - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
var inputs1 = document.getElementById(serial+'ItemCode');
inputs1.focus();
inputs1.focus();
//inputs1.focus();
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'ItemCode') {
// alert(inputs[1].name);
//alert('arif');
//inputs[i].focus();
//break;
// }
//
//}
serial++;
} else {
}
}
function SetValues2(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//var txt = document.activeElement.name;
//var numb = txt.match(/\d/g);
//numb = numb.join("");
//var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table3 = document.createElement('TABLE');
//table3.border='1';
//var tableBody3 = document.createElement('TBODY');
//table3.appendChild(tableBody3);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var lblt = document.createTextNode('Item Desc - '+arrData[0]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "100px";
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("value", '');
input.setAttribute("name", serial+'Qty');
input.setAttribute("id", serial+'Qty');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.setAttribute("data-parsley-type",'number');
input.onchange = setTwoNumberDecimal;
td.appendChild(lblt);
tr.appendChild(td);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var td = document.createElement('TD');
var lblt1 = document.createTextNode('Enter Quantity - ');
td.appendChild(lblt1);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//var inputs = document.getElementsByName(serial+'Qty');
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'Qty') {
// alert(inputs[1].name);
//inputs[i].focus();
//break;
// }
//
//}
var inputs2 = document.getElementById(serial+'Qty');
inputs2.focus();
inputs2.focus();
//inputs2.focus();
serial++;
} else {
}
//var allTags = document.body.getElementsByTagName('*');
//var ids = [];
//for (var tg = 0; tg< allTags.length; tg++) {
// var tag = allTags[tg];
// if (tag.id) {
// ids.push(tag.id);
// }
//}
//alert(ids);
//var oformo = document.forms["1ItemCode");
//alert (oForm0);
//var valdesc = document.getElementById("");
}
function SetValues(sRawData)
{
//window.location.reload();
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//$('myDynamicTable2, table1').remove();
$('#myDynamicTable2').closest('tr').remove();
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
//document.getElementById("myDynamicTable2").innerHTML = "<br>";
//document.getElementById("table1").innerHTML = "";
serial=1;
var myTableDiv = document.getElementById("myDynamicTable");
var p=1;
var u=0;
u=parseInt(arrData[0]);
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<u; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "80px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "120px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "50px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "70px";
td.style.wordWrap = "break-word";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
var tr = document.createElement('TR');
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
var myTableDiv1 = document.getElementById("myDynamicTable1");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var j=0; j<1; j++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Press F7 to Add');
btn.appendChild(btnt);
btn.title = "Press F7 to Add";
btn.value = arrData[p];
var bin=1;
//----------shortcut.add("F7", function() {
hotkeys('f7', function(event, handler){
// Prevent the default refresh event under WINDOWS system
event.preventDefault()
// alert(serial+"BinLocation");
myTableDiv2 = document.getElementById("myDynamicTable2");
table1 = document.createElement('TABLE');
table1.border='1';
tableBody1 = document.createElement('TBODY');
table1.appendChild(tableBody1);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
for (var j=0; j<1; j++) {
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'BinLocation');
input.setAttribute("id", serial+'BinLocation');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
//input.required = required;
input.onkeydown = function(){ValueChangedDesc(this);};
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Delete');
btn.appendChild(btnt);
btn.title = "Delete";
//shortcut.add("f4", function() {deleteRow(this) });
btn.onclick = function() {deleteRow(this)};
var lblt = document.createTextNode('Bin Location - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
bin++;
}
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
myTableDiv2.appendChild(table1);
var inputs = document.getElementById(serial+'BinLocation');
inputs.focus();
inputs.focus();
serial++;
});
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
myTableDiv1.appendChild(table);
}
}
function validateForm() {
var x = document.forms["myForm"]["Request"].value;
var e = document.forms["myForm"];
e=e.getElementsByTagName('input');
e=(e.length)+1;
if (x == null || x == "") {
alert("Select GRN");
return false;
}
if (e==2) {
alert("2Number of fields is invalid");
return false;
}
//alert(e) ; // 6
if ((e - 2) % 3 !== 0) {
alert("Number of fields is invalid");
return false;
}
}
I expect that without refreshing, any number of times the user selects the order and presses 'f7', the bin location fields should not duplicate.
Thanks in advance.
im using reader.onload event to get contents of csv file,
problem is the value displays in console.log() but not in DOM i.e via binding
dropped(event: UploadEvent) {
this.files = event.files;
console.log(this.files)
for (const droppedFile of event.files) {
// Is it a file?
if (droppedFile.fileEntry.isFile) {
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
fileEntry.file((file: File) => {
// Here you can access the real file
console.log(droppedFile.relativePath, file);
const fileToRead = file;
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.readAsText(fileToRead);
console.log(this.tempval) /// undefined
});
}
}}
and onFileLoad function is as follows
onFileLoad(fileLoadedEvent) {
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
var allTextLines = this.csvContent.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for ( var i = 0; i < allTextLines.length; i++) {
// split content based on comma
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for ( var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}this.tempval = linesconsole.log(this.tempval) // printing value
};
unfortunately data inside this.tempval is not accessible anywhere
not in html DOM or inside dropped() funtion. except inside onFileLoad()
im just new to typescript
thanks in advance
I am currently creating a web application that allows a user to upload an excel file into a database but before the user uploads the file I would like to allow them to check the headers of the excel file if it matches the preset on the database.
The code below allows me to display everything on the excel file:
$('#inputfile').change(function(e){
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function(e) {
var data = new Uint8Array(reader.result);
var wb = XLSX.read(data,{type:'array'});
var htmlstr = XLSX.write(wb,{sheet:"Sheet1", type:'binary',bookType:'html'});
$('#printHere')[0].innerHTML += htmlstr;
}
});
I would like to only store the excel file's header in an array and display it.
I'm new to Javascript so any help would be much appreciated.
You can do something like:
const header = []
const columnCount = XLSX.utils.decode_range(ws['!ref']).e.c + 1
for (let i = 0; i < columnCount; ++i) {
header[i] = ws[`${XLSX.utils.encode_col(i)}1`].v
}
Here is the whole example:
function extractHeader(ws) {
const header = []
const columnCount = XLSX.utils.decode_range(ws['!ref']).e.c + 1
for (let i = 0; i < columnCount; ++i) {
header[i] = ws[`${XLSX.utils.encode_col(i)}1`].v
}
return header
}
function handleFile() {
const input = document.getElementById("file")
const file = input.files[0]
if (file.type !== 'application/vnd.ms-excel') {
renderError()
}
const reader = new FileReader()
const rABS = !!reader.readAsBinaryString
reader.onload = e => {
/* Parse data */
const bstr = e.target.result
const wb = XLSX.read(bstr, { type: rABS ? 'binary' : 'array' })
/* Get first worksheet */
const wsname = wb.SheetNames[0]
const ws = wb.Sheets[wsname]
const header = extractHeader(ws)
renderTable(header)
}
if (rABS) reader.readAsBinaryString(file)
else reader.readAsArrayBuffer(file)
}
function renderTable(header) {
const table = document.createElement('table')
const tr = document.createElement('tr')
for (let i in header) {
const td = document.createElement('td')
const txt = document.createTextNode(header[i])
td.appendChild(txt)
tr.appendChild(td)
}
table.appendChild(tr)
document.getElementById('result').appendChild(table)
}
function renderError() {
const errorMsg = 'Unexpected file type'
const error = document.createElement('p')
error.setAttribute('class', 'error')
const txt = document.createTextNode(errorMsg)
error.appendChild(txt)
document.getElementById('result').appendChild(error)
throw new Error(errorMsg)
}
#result table tr td {
border: 2px solid grey;
}
#result .error {
color: red;
}
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<input type="file" onchange="handleFile()" id='file' accept=".csv"/>
<div id="result"><div>
The below code fetches data from a csv and presents in to a div as a text but am trying to convert that in to a query on fetch excel import and print then as a query
Current output when the data is imported from the excel
Example:
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
Expected output
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4');
JS fiddle demo
HTML:
<input id = "csv" type = "file" />
<div id="result"></div>
JS:
$('#csv').change(function(e) {
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var content = [];
for (var j = 1; j < lineSplit.length; j++) {
var fourColumnsData = lineSplit[j].split(',').slice(0, 4).join("','");
content.push(fourColumnsData);
}
var fileContent = content.join("')<br/>");
$('#result').html(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
});
Try the following
$('#csv').change(function(e) {
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var content = [];
for (var j = 1; j < lineSplit.length; j++) {
if (lineSplit[j].trim().length > 0) {
var fourColumnsData = "('" + lineSplit[j].split(',').slice(0, 4).join("','") + "')";
content.push(fourColumnsData);
}
}
var fileContent = content.join(",");
$('#result').html(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="csv" type="file" />
<div id="result"></div>