微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用javascript将大型CSV文件拆分为多个较小的CSV文件,做出反应

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

解决方法

是的,

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

在第5步中,您将拥有与第1步开始时相同的数据,如果要再次放置csv的标题(列名),则可以在第4步中将它们添加到数组的顶部,对于下载链接在文件名的末尾添加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    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。