简体   繁体   English

使用 javascript 读取 CSV 文件

[英]Read a CSV file with javascript

I am trying to upload a CSV file to my database with php.我正在尝试使用 php 将 CSV 文件上传到我的数据库。 I have problems with the numbers so I try to import the file in an array with javascript.我对数字有问题,所以我尝试使用 javascript 将文件导入到数组中。 I notice that the numbers of the CSV are different when I import it.我注意到导入时 CSV 的编号不同。 For example the number 23447 is "23 447"(including the space and quotes).例如数字 23447 是“23 447”(包括空格和引号)。 How can my code edit the form of the number?我的代码如何编辑数字的形式?

js数据

csv数据

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/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(",");
                            if (cells.length > 1) {
                                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.");
            }
        });
    });
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>

Just delete the spaces (whitespace characters are matched with the regex special character \\s ) then cast to a number.只需删除空格(空白字符与正则表达式特殊字符\\s匹配)然后转换为数字。 Apply this function to each csv cell value to process them:将此函数应用于每个 csv 单元格值以处理它们:

 const processNumber = str => { const strWithoutSpaces = str.replace(/\\s*/g, ''); const numberFromStr = +strWithoutSpaces; return numberFromStr; } console.log(['10 000', '3 000 000', '100'].map(processNumber))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM