0
2

SJISからUTF8に変換(GAS)

Last updated at Posted at 2024-09-14

前職にて、「csvが文字化けしてスプレッドシートで見れない!」と問い合わせが来ました。よくよく話を聞いてみたら、「古いシステムから吐き出されたcsvをGoogle Driveにアップロードし、中身を見たら文字化けしている。」とのことでした。ということで今回はSJISのファイルをUTF8に変換する関数のご紹介です。そもそも古いシステムを新しくした方が良いかもしれませんが、それまでの応急処置にどうぞ!

コード

こちらの関数に引数としてSJISの文字列を渡せば、UTF-8の文字列が返ってきます。

/**
* 受け取ったSJISの文字列をUTF-8の文字列に変換します。
* @param    {String} shiftJISString    SJISの文字列
* @return   {String}                   UTF-8の文字列
*/
function convertBlobsTextEncodingFromSjisToUtf8(shiftJISString) {
  return Utilities.newBlob(shiftJISString).getDataAsString();
}

使い方

function main() {
  const fileId = createFileWithShiftJISEncoding();
  const shiftJISFile = DriveApp.getFileById(fileId);
  const shiftJISBlob = shiftJISFile.getBlob();
  console.log(shiftJISBlob.getDataAsString());
  // ����ɂ���, ���E, ���悤�Ȃ�, ���E

  const shiftJISString = shiftJISBlob.getDataAsString('Shift-JIS');
  console.log(shiftJISString);
  // こんにちは, 世界, さようなら, 世界

  const utf8String = convertBlobsTextEncodingFromSjisToUtf8(shiftJISString);
  console.log(utf8String);
  // こんにちは, 世界, さようなら, 世界
}

/**
* rootフォルダにSJISのcsvファイルを作成します。
*/
function createFileWithShiftJISEncoding() {
  const blob = Utilities
    .newBlob('', MimeType.CSV, 'CSV(SJIS)')
    .setDataFromString('こんにちは, 世界, さようなら, 世界', 'Shift-JIS');
  const newFile = DriveApp.createFile(blob);

  const csvBlob = newFile.getBlob());
  const stringData = csvBlob.getDataAsString();
  console.log(stringData);
    // ����ɂ���, ���E, ���悤�Ȃ�, ���E
  console.log(newFile.getId());
    // fileのidが表示されます。

  return newFile.getId();
}

/**
* 受け取ったSJISの文字列をUTF-8の文字列に変換します。
* @param    {String} shiftJISString    SJISの文字列
* @return   {String}                   UTF-8の文字列
*/
function convertBlobsTextEncodingFromSjisToUtf8(shiftJISString) {
  return Utilities.newBlob(shiftJISString).getDataAsString();
}

簡単解説

使われている主な関数はUtilitiesクラスのnewBlob(data)とBlobクラスのgetDataAsString()です。

関数名 詳細
newBlob(data) 文字列から新たにBlobを作成
data: blobにするUTF-8の文字列
getDataAsString() blobデータをUTF-8の文字列として取得

SJISの文字列をこの関数に渡すと、newBlob(data)でその文字列を基にデータの処理に使われるBlobを作成します。それをgetDataAsString()でUTF-8の文字列として取り出すことで、最終的にSJISからUTF-8に変換しています。

おわりに

何かありましたらお気軽にご連絡ください!
「いいね」もお願いします!!

個人ブログではQiitaに載せきれていない内容もあるので、ご興味ありましたら是非みてください!!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2