重新排列CSV行 [英] Reorder CSV rows
问题描述
我有这段代码,基本上可以读取CSV,并应该输出一个表,在其中应重新排列CSV行的内容!
示例:
鱼; 4; 1; 33
鱼应位于第4列的第1行。
狗; 5; 2; 66
狗应该位于第二行第5列
问题是它不会在控制台上打印任何内容!你能告诉我我哪里错了吗?我应该做什么修改?
我的代码:
函数processFile (){
var fileSize = 0;
var theFile = document.getElementById( myFile)。files [0];
if(theFile){
var table = document.getElementById( myTable);
var headerLine =;
var myReader = new FileReader();
myReader.onload = function(e){
var content = myReader.result;
var lines = content.split( \r);
for(var i = 0; i< lines.length; i ++)
{
document.write(< th>));
document.write(& nbsp;& nbsp;& nbsp;& nbsp;);
document.write(< / th>);
}
for(var i = 0; i< lines.length; i ++)
{
document.write(< tr>));
for(var j = 0; j< lines.length; j ++)
{
document.write(< td>));
document.write(& nbsp;);
document.write(< / td>);
}
document.write(< / tr>);
}
函数insertData(id,content){
var dataRows = content.split( \r);
if(table){
dataRows.forEach(function {{bb $ b var x = s.split(';');
table.rows [x [2]] ] .cells [x [1]]。textContent = x [0];
});
}
}
}
myReader.readAsText(theFile);
}
返回false;
} //结束
所以,我举一个很大的例子,再次为您做了一切。
我想您可以在代码中处理它,或以我的示例为例。
以下是在您的情况下可以安全使用的主要功能:
//用于交换值
函数swap(arr,a,b){
var tmp = arr [一种];
arr [a] = arr [b];
arr [b] = tmp;
return arr;
}
//用于重新排序行a< => b
函数reorderLine(csvArray,a,b){
return swap(csvArray,a,b );
}
//用于重新排序一个col值a&=; b b
函数reorderColumn(csvLine,a,b){
return swap(csvLine.split (;),a,b).join(';');
}
//用CSV数据创建表
函数csvArrayToTable(csvArray,selectorId){
var html = [< table cellpadding = '10' border ='1'>];
csvArray.map(function(lines){
html.push(< tr>);
var cols = lines.split(;);
html .push( th> + cols [0] + // th);
cols.shift();
cols.map(function(val){
html.push(< td> + val +< / td>);
});
html.push(< / tr>);
});
html.push(< / table>);
document.getElementById(selectorId).innerHTML = html.join(’’);
}
您也可以使用一个可行的示例,其中包含上传文件(点击在代码底部运行代码段,并进行整页测试):
//用于交换值函数swap(arr,a,b){var tmp = arr [a]; arr [a] = arr [b]; arr [b] = tmp; return arr;} //对于重新排序行a< => bfunction reorderLine(csvArray,a,b){console.log(’reorderLine',csvArray,a,b); return swap(csvArray,a,b);} //用于对一个col值重新排序a&=; b函数reorderColumn(csvLine,a,b){console.log(’reorderColumn’,csvLine,a,b); return swap(csvLine.split(;),a,b).join(';');} //创建带有csv数据功能的表csvArrayToTable(csvArray,selectorId){var html = [< table cellpadding = '10'border ='1'>]; csvArray.map(function(lines){html.push(< tr>); var cols = lines.split(;); html.push( thth> + cols [0] + < / th>); cols.shift(); cols.map(function(val){html.push(< td> + val +< / td>);}); html.push (< / tr>);}); html.push(< / table>); document.getElementById(selectorId).innerHTML = html.join('');} //初始化元素var rawCsvFile = document.getElementById( csvInput); var rawCsv = document.getElementById( rawCsv); var reorderedRawCsv =文档。 getElementById( reorderedRawCsv); var lines = document.getElementById( lines); var lineA = document.getElementById( lineA); var lineB = document.getElementById( lineB); var colA = document.getElementById( colA); var colB = document.getElementById( colB); var apply = document.getElementById( apply); var reset = document.getElementById( reset); var rawCsvData,reorderCsvData; //文件上传rawCsvFile .addEventListener( change,function(){//阅读器var reader = new FileReader(); //文件已加载reader.onload = function(e){//如果未定义则取消if(!reader.result || typeof reader.result!= string)return; //从新的FileReader()获取结果rawCsvData = reader.result.split(/ [\r\n] + / g); //分割行rawCsv.innerHTML = reader.result; //在文本区域中显示reorderedR awCsvData = rawCsvData; //在启动函数showCsvValueInForm(){处克隆数据} //空字段lines.innerHTML =; lineA.innerHTML =; lineB.innerHTML =; colA.innerHTML =; colB.innerHTML =; //以原始CSV文本区域显示reorderedRawCsv.innerHTML = reorderedRawCsvData.join( \r\n); //将On var中的All选项添加到All = document.createElement(’option’); toAll.value =全部; toAll.innerHTML =全部; lines.appendChild(toAll); //处理行更改reorderedRawCsvData.map(function(val,i){var lineOpt = document.createElement('option'); lineOpt.value = i; lineOpt.innerHTML = i +- +(val.split(' ;'))[0]; //在行选择中添加选项lines.appendChild(lineOpt.cloneNode(!! 1)); lineA.appendChild(lineOpt.cloneNode(!! 1)); lineB.appendChild(lineOpt); }); //处理col变化var nCol = rawCsvData [0] .split(’;’); nCol.map(function(val,i){var colOpt = document.createElement('option'); colOpt.value = i; colOpt.innerHTML = i; //在col中添加选项会选择colA.appendChild(colOpt.cloneNode( !! 1)); colB.appendChild(colOpt);}); //创建表csvArrayToTable(reorderedRawCsvData, reorderedCsvTable); } //用重新排序的csv数据showCsvValueInForm();填充select,option和table。 //应用事件,更改顺序apply.addEventListener( click,function(){//重新排序行var lineAOpt = lineA.options [lineA.selectedIndex] .value; var lineBOpt = lineB.options [lineB.selectedIndex]。值; if(lineAOpt!== lineBOpt)reorderedRawCsvData = reorderLine(reorderedRawCsvData,lineAOpt,lineBOpt); //重新排序col(全部或仅一个)var colAOpt = colA.options [colA.selectedIndex] .value; var colBOpt = colB。 options [colB.selectedIndex] .value; if(colAOpt!== colBOpt)if(lines.value == all){reorderedRawCsvData = reorderedRawCsvData.map(function(val,i){return reorderColumn(val,colAOpt,colBOpt );});}其他{reorderedRawCsvData [lines.value] = reorderColumn(reorderedRawCsvData [lines.value],colAOpt,colBOpt);} //再次填充showCsvValueInForm();}); //使用原始值重置表单reset.addEventListener( click,function(){if(confirm(您确定吗?))){// reset reorderedRawCsvData = rawCsvData; //再次填写showCsvValueInForm();}} ); } //以文本阅读器的形式读取上载的csv文件。readAsText(event.target.files [0],'utf-8');});
body {padding:10px;背景:#eee;文字对齐:左;字体家族:sans-serif; } fieldset {width:80%;背景:#fff; }
< html> < head> < title> CSV重新排序< / title> < / head> < body> < h1>重新排序CSV< / h1> < fieldset> < h3>步骤1-原始CSV< / h3> < small>加载CSV文件(未嵌套)< / small> < br /> < input type = file id = csvInput> < br /> < br /> < div> < textarea id = rawCsv placeholder =正在等待文件...>< / textarea> < / div> < / fieldset> < br /> < fieldset> < h3>步骤2-重新排序选项< / h3> < small>选择如何排序CSV数据< / small>。 < br /> < table> < tr> < td>行< / td> < td><选择id = lineA>< / select>< / td> < td>< / td> < td><选择id = lineB>< / select>< / td> < / tr> < tr> < td>列< / td> < td><选择id = colA>< / select>< / td> < td>< / td> < td><选择id = colB>< / select>< / td> < td> on< / td> < td><选择id = lines>< / select>< / td> < / tr> < tr> < td colspan = 4>< button id = apply> Apply< / button>& nbsp;< button id = reset>重置< / button>< / td> < / tr> < / table> < / fieldset> < br /> < fieldset> < h3>步骤3-重新排序CSV< / h3> < small>获取重新排序的值< / small> < br /> < div> < textarea id = reorderedRawCsv placeholder =正在等待选项...>< / textarea> < / div> < div> < h3>在表中重新排序CSV< / h3> < div id = reorderedCsvTable> < small>等待文件。< / small> < br /> < / div> < / div> < / fieldset> < / body>< / html>
享受! / p>
I have this code which basically reads a CSV and should output a table where the CSV row content should be reordered!
Example :
fish;4;1;33
fish should be at 1 row column 4.
dog;5;2;66
dog should be at 2nd row column 5
The problem is that it doesn't print anything, neither at the console! Can you please show me where I am wrong? What modifications should I do?
My code:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var i = 0; i <lines.length; i++)
{
document.write("<th>");
document.write(" ");
document.write("</th>");
}
for (var i = 0; i <lines.length; i++)
{
document.write("<tr>");
for (var j = 0; j <lines.length; j++)
{
document.write("<td>");
document.write(" ");
document.write("</td>");
}
document.write("</tr>");
}
function insertData(id, content) {
var dataRows = content.split("\r");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
});
}
}
}
myReader.readAsText(theFile);
}
return false;
} //end
So, i did everything again for you with a big example. I think you can handle it in your code, or take mine in the example.
Here are the main functions you can safely use in your case :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
And a working example you can use too, upload file is included (click on Run code snippet at the bottom of the post, and full page to test) :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
console.log('reorderLine',csvArray,a,b);
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
console.log('reorderColumn',csvLine,a,b);
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
// init element
var rawCsvFile = document.getElementById("csvInput");
var rawCsv = document.getElementById("rawCsv");
var reorderedRawCsv = document.getElementById("reorderedRawCsv");
var lines = document.getElementById("lines");
var lineA = document.getElementById("lineA");
var lineB = document.getElementById("lineB");
var colA = document.getElementById("colA");
var colB = document.getElementById("colB");
var apply = document.getElementById("apply");
var reset = document.getElementById("reset");
var rawCsvData, reorderCsvData;
// file uploaded
rawCsvFile.addEventListener("change", function() {
// reader
var reader = new FileReader();
// the file is loaded
reader.onload = function(e) {
// cancel if undefined
if(!reader.result || typeof reader.result != "string") return;
// Get result from new FileReader()
rawCsvData = reader.result.split(/[\r\n]+/g); // split lines
rawCsv.innerHTML = reader.result; // show in textarea
reorderedRawCsvData = rawCsvData; // clone data at start
function showCsvValueInForm(){
// empty fields
lines.innerHTML = "";
lineA.innerHTML = "";
lineB.innerHTML = "";
colA.innerHTML = "";
colB.innerHTML = "";
// Show in Raw CSV textarea
reorderedRawCsv.innerHTML = reorderedRawCsvData.join("\r\n");
// Add All option in On
var toAll = document.createElement('option');
toAll.value = "all";
toAll.innerHTML = "All";
lines.appendChild(toAll);
// handle line change
reorderedRawCsvData.map(function(val,i){
var lineOpt = document.createElement('option');
lineOpt.value = i;
lineOpt.innerHTML = i + " - " +(val.split(';'))[0];
// add options in line selects
lines.appendChild(lineOpt.cloneNode(!!1));
lineA.appendChild(lineOpt.cloneNode(!!1));
lineB.appendChild(lineOpt);
});
// handle col change
var nCol = rawCsvData[0].split(';');
nCol.map(function(val,i){
var colOpt = document.createElement('option');
colOpt.value = i;
colOpt.innerHTML = i;
// add options in col selects
colA.appendChild(colOpt.cloneNode(!!1));
colB.appendChild(colOpt);
});
// create table
csvArrayToTable(reorderedRawCsvData,"reorderedCsvTable");
}
// fill select, option and table with the reordered csv data
showCsvValueInForm();
// apply event, change the order
apply.addEventListener("click", function() {
// reordering line
var lineAOpt = lineA.options[lineA.selectedIndex].value;
var lineBOpt = lineB.options[lineB.selectedIndex].value;
if(lineAOpt !== lineBOpt) reorderedRawCsvData = reorderLine(reorderedRawCsvData,lineAOpt,lineBOpt);
// reordering col (all or only one)
var colAOpt = colA.options[colA.selectedIndex].value;
var colBOpt = colB.options[colB.selectedIndex].value;
if(colAOpt !== colBOpt)
if(lines.value == "all"){
reorderedRawCsvData = reorderedRawCsvData.map(function(val,i){
return reorderColumn(val,colAOpt,colBOpt);
});
}else{
reorderedRawCsvData[lines.value] = reorderColumn(reorderedRawCsvData[lines.value],colAOpt,colBOpt);
}
// fill again
showCsvValueInForm();
});
// reset the form with raw values
reset.addEventListener("click", function() {
if (confirm("Are you sure ?")) {
// reset
reorderedRawCsvData = rawCsvData;
// fill again
showCsvValueInForm();
}
});
}
// read the uploaded csv file as text
reader.readAsText(event.target.files[0], 'utf-8');
});
body { padding:10px; background:#eee; text-align: left; font-family: sans-serif; }
fieldset { width:80%; background:#fff; }
<html>
<head>
<title>CSV Reorder</title>
</head>
<body>
<h1>Reorder CSV</h1>
<fieldset>
<h3>Step 1 - Raw CSV</h3>
<small>Load a CSV file (not nested)</small>
<br />
<input type="file" id="csvInput">
<br />
<br />
<div>
<textarea id="rawCsv" placeholder="Waiting for a file..."></textarea>
</div>
</fieldset>
<br />
<fieldset>
<h3>Step 2 - Reordering Option</h3>
<small>Choose how to order the CSV data</small>
<br />
<table>
<tr>
<td>Line</td>
<td><select id="lineA"></select></td>
<td><=></td>
<td><select id="lineB"></select></td>
</tr>
<tr>
<td>Column</td>
<td><select id="colA"></select></td>
<td><=></td>
<td><select id="colB"></select></td>
<td>on</td>
<td><select id="lines"></select></td>
</tr>
<tr>
<td colspan="4"><button id="apply">Apply</button> <button id="reset">Reset</button></td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<h3>Step 3 - Reordered CSV</h3>
<small>Get the reordered values</small>
<br />
<div>
<textarea id="reorderedRawCsv" placeholder="Waiting for options..."></textarea>
</div>
<div>
<h3>Reordered CSV in a table</h3>
<div id="reorderedCsvTable">
<small>Waiting for a file..</small>
<br />
</div>
</div>
</fieldset>
</body>
</html>
Enjoy !
这篇关于重新排列CSV行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!