Search code examples
google-apps-script

How can export a CSV with Shift-Jis encoding in Google Apps Script?


I want export a CSV with Shift-Jis encoding in Google Apps Script.

This is my code:

function exportToCSV() {
  var csvContent = '歳以上,三井ホームコンポーネント㈱・横浜 -- HLⅢ 片流れ・ジョイント水切り250 2個入 B'; 
  var shiftJisBlob = Utilities.newBlob(csvContent, 'text/csv').setDataFromString(csvContent, 'Shift_JIS');
  shiftJisBlob.setName('data_shiftjis.csv');
  var file = DriveApp.createFile(shiftJisBlob);
  Logger.log('File CSV : ' + file.getUrl());
}

This is Result opening by Notepad++: It can create CSV with Shift-Jis encoding, but some character is not correct. enter image description here

How can export a CSV with Shift-Jis encoding in Google Apps Script?


Solution

  • Although I'm not sure whether I could correctly understand your expected result, how about the following answer?

    When I saw your text 歳以上,三井ホームコンポーネント㈱・横浜 -- HLⅢ 片流れ・ジョイント水切り250 2個入 B and your showing image, it seems that the extended characters like and . I guessed that this might be the reason for your current issue. In this case, how about using CP932 instead of Shift-JIS? When this is reflected in your script, please modify it as follows.

    From:

    var csvContent = '歳以上,三井ホームコンポーネント㈱・横浜 -- HLⅢ 片流れ・ジョイント水切り250 2個入 B'; 
    var shiftJisBlob = Utilities.newBlob(csvContent, 'text/csv').setDataFromString(csvContent, 'Shift_JIS');
    

    To:

    var csvContent = '歳以上,三井ホームコンポーネント㈱・横浜 -- HLⅢ 片流れ・ジョイント水切り250 2個入 B';
    var shiftJisBlob = Utilities.newBlob("", 'text/csv').setDataFromString(csvContent, 'CP932');
    
    • I guess that in this case, CP932, Windows-31J and MS932 show the same results.