javascript下載csv檔案

參考自: https://dotblogs.com.tw/shihgogo/2017/05/31/090831

function createCsvFile(){
  var fileName = "ooooo.csv";//匯出的檔名
  var data = getRandomData();
  var blob = new Blob([data], {
    type : "application/octet-stream"
  });
  var href = URL.createObjectURL(blob);
  var link = document.createElement("a");
  document.body.appendChild(link);
  link.href = href;
  link.download = fileName;
  link.click();
}

//隨機產生資料
function getRandomData() {
  var header = "第一欄,第二欄,第三欄,第四欄,第五欄\n";
  var data = "";
  for (var i = 0; i < 50; i++) {
      for (var j = 0; j < 5; j++) {
        if(j>0){
            data = data + ",";
        }
        data = data + "Item" + i + "_" + j;
      }
      data = data + "\n";
  }
  return header+data;
}

 

posted @ 2019-09-19 10:29  日光之下无新事  阅读(351)  评论(0编辑  收藏  举报