26 February 2018

Download CSV Shift-JIS SJIS Angular 2+

export-csv-ecl.html
Javascript
<!doctype html>
<html>
   <head>
      <script src="ecl_array.js"></script>
      <script>
         function download_csv() {
          var content_file = '説明会内容\n1,あああ,いいい\n2,ううう,えええ';
         
          var str_array = ECL.charset.Unicode.parse(content_file);
          var sjis_array = ECL.charset.convert_array(str_array, "SJIS");
          var uint8_array = new Uint8Array(sjis_array);
         
          var blob = new Blob([uint8_array], { type: "text/csv;" });
         
          var url = window.URL.createObjectURL(blob);
         
          if (navigator.msSaveOrOpenBlob) {
             navigator.msSaveBlob(blob, 'demo-Shift-JIS.csv');
          } else {
             var a = document.createElement('a');
             a.href = url;
             a.download = "demo-Shift-JIS.csv";
             document.body.appendChild(a);
             a.click();
             document.body.removeChild(a);
          }
            window.URL.revokeObjectURL(url);
         }   
      </script>
   </head>
   <body>
      <button onclick="download_csv()">Download CSV</button> 
   </body>
</html>

Download example
Nguồn: gitHub
Export CSV Shift-JIS SJIS Angular 2+

npm install encoding-japanese --save
npm install @types/node --save
export-csv-encoding.ts
Angular 2+
import {
   Component,
} from '@angular/core';
declare var require: any;
@Component({
   selector: 'export-csv-encoding',
   template: '<button (click)="downloadFile()">Click me to download CSV</button>',
   styleUrls: ['./style.scss']
})
export class CreateCSV {

   constructor() {}

   downloadFile() {
      const content_file = 'A,"B",C\n1,"a,b,c",d\n2,E,F';

      const encoding = require('encoding-japanese');
      const str_array = encoding.stringToCode(content_file);
      const sjis_array = encoding.convert(str_array, "SJIS", "UNICODE");
      const uint8_array = new Uint8Array(sjis_array);

      const blob = new Blob([uint8_array], {
         type: "text/csv"
      });
      const url = window.URL.createObjectURL(blob);

      if (navigator.msSaveOrOpenBlob) {
         navigator.msSaveBlob(blob, 'demo-Shift-JIS.csv');
      } else {
         const a = document.createElement('a');
         a.href = url;
         a.download = "demo-Shift-JIS.csv";
         document.body.appendChild(a);
         a.click();
         document.body.removeChild(a);
      }
      window.URL.revokeObjectURL(url);
   }
}
Download.zip
Nguồn: npmjs & Github

ngx-shift-jis



NOTE: Cách fix để hiển thị dấu phẩy trong cùng column
var content_file = 'A,"B",C\n1,"a,b,c",d\n2,E,F';

1 nhận xét:

  1. If input only number eg: "1234567" => export cv file with UTF-8 not Shift-JIS ??? I don't know how to fix it ! Please supprot me :(

    ReplyDelete

 

BACK TO TOP

Xuống cuối trang