JavaScript - 读取 CSV(Comma-Separated Values)文件

文章目录

  • 示例
    • 效果
    • 代码
  • 参考

示例

效果

JavaScript - 读取 CSV(Comma-Separated Values)文件_第1张图片

代码

DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>读取 CSV(Comma-Separated Values)文件title>
    head>
    <body>
        
        
        <input type="file" accept="text/csv" />
        
        
        <progress value="0">progress>

        <script type="text/javascript">
            window.onload = (event) => {
                // console.log(event);
                main();
            }
            
            function main() {
                var inputFile = document.querySelector("input[type='file']");
                
                inputFile.onchange = (event) => {
                    // console.log(event);
                    var file = inputFile.files[0];
                    
                    var fileReader = new FileReader();
                    fileReader.readAsText(file, "utf-8");
                    
                    // 显示进度
                    var progress = document.querySelector("progress");
                    progress.max = file.size;
                    progress.value = 0;
                    fileReader.onprogress = (event) => {
                        // console.log(event);
                        progress.value = event.loaded;
                    }
                    
                    fileReader.onload = (event) => {
                        console.log(event, fileReader);
                        var result = fileReader.result;
                        console.log(result); // 读取的结果
                    }
                }
            }
        script>
    body>
html>

参考

JS 读取并解析csv文件 —— 前端踩坑13

你可能感兴趣的:(HTML,&,CSS,&,JavaScript,javascript,CSV,逗号分隔值文件格式)