AI-Powered Translation for Univer Sheets: Automating Cell Content Translation

Background

With the globalization of work and study, communication across languages has become increasingly important. For users who work with spreadsheets containing multilingual data, the need to translate content in cells becomes a common requirement.

Traditional translation methods often involve manual copying and pasting or relying on external tools, both of which are tedious and time-consuming. To address this challenge, we developed the — — AI Cell Translator , an AI-powered tool that automatically translates the content of selected cells in Univer Sheets . This tool supports batch translation (up to 100 cells) and facilitates translation between English and Chinese.

Official Website :Univer Go

Solution

The AI Cell Translator script leverages AI technology to provide fast and efficient translation capabilities by integrating the GLM-4 API. The script can be embedded in Univer Go , allowing users to simply select one or more cells and then click the translation option from the ribbon or right-click context menu. The translation result is automatically filled back into the original cells, greatly improving efficiency in data handling.

Univer Go is a powerful script writing and execution tool designed for cross-platform environments, helping developers create and run automation scripts, connect to databases, and build custom applications. With its simple interface and efficient workflows, Univer Go offers an easy-to-use programming environment, suitable for both beginners and professional developers.

Key Features:

- Direct translation of selected cell content.

- Supports batch translation (up to 100 cells).

- Supports translation between English and Chinese.

- Easily accessible from the ribbon menu or right-click context menu.

Usage Steps:

1. Select one or more cells containing text.

2. Choose the translation option (either “Translate to English” or “Translate to 中文”) from the ribbon or right-click menu.

This solution saves users time and effort, eliminating the need for manual translation and streamlining the process.

Implementation

Below is a detailed explanation of the AI Cell Translator script implementation, along with an analysis of key methods:

Key Parts of the Script

  1. API Configuration
const AI_ENDPOINT = "https://open.bigmodel.cn/api/paas/v4";
const AI_KEY = "[YOUR_API_KEY]";

- AI_ENDPOINT: This variable defines the endpoint for the AI translation API.

- AI_KEY: Stores the API key required for accessing the API. Note: This is a demo API key, and users should replace it with their own API key for production use.

2. onOpen Function

function onOpen() {
    univerAPI.createMenu({
        id: 'translate-to-en',
        title: 'Translate to English',
        action: () => translateSelectedCells("English"),
    }).appendTo('ribbon.start.others');

    univerAPI.createMenu({
        id: 'translate-to-cn',
        title: 'Translate to 中文',
        action: () => translateSelectedCells("中文"),
    }).appendTo('ribbon.start.others');
}

- This function runs automatically when Univer Sheets is opened. It creates two menu items, “Translate to English” and “Translate to 中文”, which users can click to translate selected cells.

- The translation feature is easily accessible through the ribbon menu.

3. translate Function

async function translate(text, target = "中文") {
    const prompt = `
    # You are a translation expert. 
    ## Rules
    Please return the translation result only, without any other text.
    ## Job
    Please translate the following text into ${target} language:
    ${text}
    `;
    const response = await fetch(AI_ENDPOINT + '/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + AI_KEY,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            model: 'glm-4-flash',
            messages: [
                {
                    role: 'user',
                    content: prompt
                }
            ]
        })
    }).then(response => response.json())

    return response.choices[0].message.content;
}

- The translate function is the core translation function. It takes the text to be translated and the target language (default is Chinese).

- It uses the GLM-4 API to translate the text and returns the translation result.

4. translateSelectedCells Function

async function translateSelectedCells(target = "中文") {
    if (isTranslating) {
        showMessage({ content: 'A translation task is already running. Please wait.' });
        return;
    }

    const workbook = univerAPI.getActiveWorkbook();
    const sheet = workbook.getActiveSheet();
    const activeRange = workbook.getActiveRange();
    const cells = activeRange.getValues();

    if (!cells.length) {
        showMessage({ content: 'Please select a range' });
        return;
    }

    const totalCells = cells.reduce((count, row) =>
        count + row.filter(cell => cell).length, 0);

    if (totalCells > 100) {
        showMessage({
            content: 'Too many cells selected (max: 100). Please select fewer cells.'
        });
        return;
    }

    try {
        isTranslating = true;
        const offsetX = activeRange.getRange().startColumn;
        const offsetY = activeRange.getRange().startRow;

        for (let i = 0; i < cells.length; i++) {
            const rows = cells[i];
            for (let j = 0; j < rows.length; j++) {
                const cell = rows[j];
                if (!cell) continue;
                const result = await translate(cell, target);
                sheet.getRange(offsetY + i, offsetX + j).setValue(result);
            }
        }

        setTimeout(() => showMessage({ content: 'Translation completed successfully' }), 100);
    } catch (error) {
        showMessage({ content: `Translation failed: ${error.message}` });
    } finally {
        isTranslating = false;
    }
}

- The translateSelectedCells function handles the translation logic. It first checks if a translation task is already running, then retrieves the selected cells from the active range.

- If the user selects more than 100 cells, the function prompts them to select fewer cells.

- It translates each selected cell’s content and fills the translated result back into the corresponding cells.

Conclusion

With the AI Cell Translator script, users can easily translate content in Univer Sheets , saving valuable time and effort. By embedding this AI-powered tool directly into the spreadsheet interface, it allows users to perform translations without leaving the sheet.

In a production environment, we recommend replacing the API key and using a professional translation service to ensure stable and accurate translations. If you need an efficient translation tool within Univer Sheets, this powerful AI translator is a great option!

Get rid of excel and deploy a private spreadsheet system

Univer Go Launches AI-Powered API Writing Assistance

Facade API — How Univer Enhances the Development Experience

How to Implement Worksheet or Range Protection in Univer