问题描述
我有一个很大的csv文件,甚至有几百万条记录。是否可以在客户端使用javascript将这个大文件拆分为几个较小的文件(例如100k条记录)?
解决方法
是的,
- 用户选择文件
- 您在加载的文件上添加事件,并将结果存储在变量中
- 使用
filedata.split("\n")
将文件分成几行(创建大项目数组) - 将数组的每100k部分保存到一个变量中,并使用
array.join("\n")
创建新文件内容。 - 为每个文件创建一个下载链接
在第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