【问题标题】:Convert CSV charset from Shift-JIS to UTF-8将 CSV 字符集从 Shift-JIS 转换为 UTF-8
【发布时间】:2021-05-29 19:46:06
【问题描述】:

我想做什么

  1. 从 CSV 文件中获取数据(字符集:Shift-JIS)
  2. 将字符集转换为 UTF-8
  3. 将值设置到 Google 电子表格中

我在第 2 步遇到问题。

问题

我在将 Shift-JIS CSV 转换为 UTF-8 CSV 时遇到问题。
Google 电子表格中的字符串都是乱码。

这是我的 Google 电子表格的代码和屏幕截图:

function myFunction() {
  const fileId = 'xxxxxx' // Shift-JIS CSV file's ID
  const blob = DriveApp.getFileById(fileId).getBlob();
  const csv = blob.getDataAsString();

  const newBlob = Utilities.newBlob('', MimeType.CSV).setDataFromString(csv, 'UTF-8');
  const newCSV = newBlob.getDataAsString();

  const values = Utilities.parseCsv(newCSV);

  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}

预期:

代替:

【问题讨论】:

    标签: csv google-apps-script google-sheets utilities


    【解决方案1】:

    我认为在您的脚本中,需要从文件中检索值(shift-jis 的 CSV 数据)为shift-jis。在这种情况下,不需要使用const newBlob = Utilities.newBlob('', MimeType.CSV).setDataFromString(csv, 'UTF-8');。所以当你的脚本被修改后,就变成了如下。

    修改脚本:

    function myFunction() {
      const fileId = 'xxxxxx' // Shift-JIS CSV file's ID
      const blob = DriveApp.getFileById(fileId).getBlob();
    
      const csv = blob.getDataAsString("shift-jis");  // Modified
    
      const values = Utilities.parseCsv(csv);
      const sheet = SpreadsheetApp.getActiveSheet();
      sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
    }
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-01
      • 2016-09-06
      • 2014-05-02
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多