How to easily translate between Japanese and English in Google Sheets.

JavaScript

I will introduce how to easily translate text within a spreadsheet into Japanese and English using Google Apps Script.

Used Technologies

  • Google Sheets: Used for data storage and management.
  • Google Apps Script: A scripting language for writing programs primarily to automate Google Sheets.
  • This scripting language is based on JavaScript.
  • Google Apps Script UI Service: Used to add custom menus to a spreadsheet.
  • LanguageApp API: An API used for translation within Google Apps Script.
  • JSON: Uses JSON format to easily handle arrays and objects.
  • Data Range: Specifies a particular range within a spreadsheet to retrieve data.
  • Data Validations: Determines whether specific input rules are set for a cell.
  • Formulas: Reviews the formulas used in the cells of a spreadsheet.
  • UI Alerts: Displays error information or success messages to the user.

Features

  • Adding a Custom Menu: Adding a “Translate” menu to the spreadsheet, offering translation options between Japanese and English.
  • Copying Sheets: Copies the active sheet to create a new sheet. The name of the new sheet is also translated.
  • Translating Text in Cells: Translates cells containing text in Japanese or English into the target language.
  • Skipping Formulas: If a cell contains a formula, it is excluded from the translation.
  • Considering Data Validation: Cells with set input rules are excluded from the translation.
  • Error Handling: If an error occurs during translation, the user is notified of the cell’s location.
  • Success Message: A confirmation message is displayed when the translation is successful.
  • Support for Batch Translation: Includes the ability to translate multiple texts at once (however, this feature is not directly used in the script at the moment).

Sauce Code

JavaScript
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Translation')
    .addItem('Japanese > English', 'jpToEn')
    .addItem('English > Japanese', 'EnToJp')
    .addToUi();
}

function jpToEn() {
  translate('ja', 'en');
}

function EnToJp() {
  translate('en', 'ja');
}

function batchTranslate(textArray, inputLang, outputLang) {
  var concatenatedText = textArray.join('|');
  var translatedText = LanguageApp.translate(concatenatedText, inputLang, outputLang);
  return translatedText.split('|');
}

function translate(inputLang, outputLang) {
  var errorCells = [];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  
  var translatedSheetName = LanguageApp.translate(sheet.getName(), inputLang, outputLang);
  var dest = sheet.copyTo(ss);
  dest.setName(translatedSheetName);
  
  var originalRange = sheet.getDataRange();
  var originalValues = originalRange.getValues();
  var originalFormulas = originalRange.getFormulas();
  var dataValidations = originalRange.getDataValidations();

  var translatedValues = JSON.parse(JSON.stringify(originalValues));

  for (var i = 0; i < originalValues.length; i++) {
    for (var j = 0; j < originalValues[i].length; j++) {
      if (dataValidations && dataValidations[i][j] !== null) {
        continue;  // Skip cells with data validation
      }
      if (originalFormulas[i][j] === "" && isNaN(originalValues[i][j]) && typeof originalValues[i][j] === "string") {
        try {
          var translatedText = LanguageApp.translate(originalValues[i][j], inputLang, outputLang);
          dest.getRange(i + 1, j + 1).setValue(translatedText);
        } catch (e) {
          errorCells.push(`${String.fromCharCode(65 + j)}${i + 1}`);
        }
      }
    }
  }

  if (errorCells.length > 0) {
    SpreadsheetApp.getUi().alert(`Errors occurred in the following cells: ${errorCells.join(", ")}. Please check these cells manually.`);
  } else {
    SpreadsheetApp.getUi().alert('Translation completed. Please check the new sheet.');
  }
}

// MIT License
// Copyright (c) 2023 [ANJI]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

How to Use

  1. Opening Google Spreadsheet: Open a new spreadsheet or select an existing one.
  2. Opening the Script Editor: Select “Apps Script” from the “Extensions” menu to open the script editor.
  3. Pasting the Code: Copy and paste the provided JavaScript code into the script editor.
  4. Save and Close: Save the script and then close the editor.
  5. “Translate” Menu Added to Spreadsheet: After closing the script editor, a “Translate” menu will have been added to the spreadsheet when you return to it.
  6. Selecting Translation Options: Choose the language pair (either “Japanese > English” or “English > Japanese”) from the “Translate” menu.
  7. Executing the Translation: After selecting the option, the script automatically translates the content of the active sheet and creates a new sheet.
  8. Error Check: If an error occurs, its location is notified through an alert. Manual correction is required.
  9. Confirmation Message: A confirmation message is displayed when the translation is successful.

コメント

タイトルとURLをコピーしました