重新排序CSV行

时间:2017-10-21 08:26:13

标签: javascript arrays csv html-table

我有这个基本上读取CSV的代码,应该输出一个表格,其中应该重新排序CSV行内容!

示例:

fish;4;1;33 鱼应该在第1列第4列。

dog;5;2;66 狗应该在第2排第5列

问题是它不能在控制台上打印任何东西!你能告诉我我错在哪里吗?我应该做些什么修改?

我的代码:

 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("&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>");
                 }

                 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

1 个答案:

答案 0 :(得分:0)

所以,我用一个很好的例子再次为你做了一切。 我认为你可以在你的代码中处理它,或者在我的示例中使用它。

以下是您可以安全使用的主要功能:

        //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('');
        }

还有一个可以使用的工作示例,包含上传文件(点击帖子底部的运行代码段,以及测试的完整页面):

&#13;
&#13;
//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');

});
&#13;
body { padding:10px; background:#eee; text-align: left; font-family: sans-serif; }
fieldset { width:80%;  background:#fff; }
&#13;
<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>&nbsp;<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>
&#13;
&#13;
&#13;

享受!