使用 javascript 将大型 CSV 文件拆分为多个较小的 CSV 文件,作出反应

Split large CSV file into multiple smaller CSV files using javascript, react

我有一个很大的csv文件,甚至有几百万条记录。是否可以在客户端使用 javascript 将这个大文件拆分成几个较小的文件(例如 100k 条记录)?

是的,有可能,

  1. 用户选择一个文件
  2. 您在加载文件时添加事件并将结果存储在变量中
  3. 使用filedata.split("\n")将文件拆分为多行(创建大量项目)
  4. 将数组的每个 100k 部分保存到一个变量中并使用 array.join("\n") 创建新文件内容。
  5. 为每个文件创建一个下载link

在第 5 步中,您将获得与第 1 步中相同的数据,如果您想再次放置 csv 的 header(列名),您可以将它们添加到数组的顶部第四步,下载link在文件名末尾添加csv。这里有一个代码应该是什么样子的例子。

// function called on file change event
function updatefile(event) {
     var reader = new FileReader();
     reader.onload = function () {
        // you do your split function here 
        var allItems = reader.result.split("\n");
        // 1) you split allitems into smaller arrays of 100k
        // 2) you save each item in to array and convert it to text again
        // it is possible that you need to add your csv header to the top
        // of the array  (for item 0 it is already there) for others 
        // (itms100Array[1].unshift(allItems[0])
        var item100kFileData[0] = item100kArray[0].join("\n");
        // 3) Create an object URL for a blob that contain the item
        // 4) add the download link to HTML       
     };
     reader.readAsText(event.target.files[0]);
     // other code here
} // end of function file update