How to import/export Android string resource to Excel for localization?
Asked Answered
O

11

47

I use Android Studio in app development. I want to translate strings by exporting/importing the Android language resources (strings.xml) to Excel file (xlsx). What is the best way to do it?

Octosyllabic answered 6/6, 2015 at 15:22 Comment(0)
S
30

If anyone else needed the answer,

from res -> strings -> right click-> Open Translations Editor. Select data/variable you need then copy and paste data from Translations Editor to excel . done.

image from android studio v2.2

Specification answered 8/8, 2016 at 10:55 Comment(15)
Just tried it on 10.11.6 by selecting all (Cmd-A) then Copy and Paste to Numbers or Notes. No luck.Imprimis
For anyone Mac users having the same issue as me, make sure to copy using (Ctrl+C), as pointed out by @ShellDudeImprimis
Yea just Ctrl+C from Android Studio, then Command+V to Google Sheets works perfectly!Eleemosynary
Is there anyway to copy from Excel sheet to Android Studio?Striated
@ChintanShah just use ctrl+c from excel.and use ctrl+v in Translations EditorAvail
@Avail That I know! I mean copying all fields of one column and pasting it to Translator Editor in one go. Do you know how to do it?Striated
@ChintanShah you need to click the first fields and press SHIFT.then click the last fields.so all fieldds can select.Avail
Ctrl-C does not copy for me although Ctrl-A selects all. AS 2.3.3 OSX 10.11.6Vase
Is there any way to copy comments too? I need to send some usable file to the translation company, and they do not have Android Studio. (fortunately or unfortunately) I have added screen names in the comments to make them translation easier.Lifeguard
You will have problems with whitespace characters: \n, html tags: <b> etc.Peggie
I can't copy it back to the editor :( does anyone know what the reason could be? I am using version 3.0.1Tyndale
How does it work now? I can neither select all the fields nor copy any of them in AS 3.2.Brancusi
@Brancusi It doesn't work anymore after a recent update. I'm also using version 3.2 and nothing happens after pressing Ctrl+A. Previously you could select all values with this combination.Botts
I'm pretty sure that the original question was not asking how to do this one at a time.Stagnant
Works only one at a time, which is pointelss.Precast
C
6
  1. Export Strings resource file to csv
  2. Get its content translated(probably from google translate)
  3. convert back the Translated file to Strings.xml(android string resource file)

I used http://convertcsv.com/csv-to-xml.htm this website for converting csv file to strings resource file

need to mention Custom output template to convert it to strings resource file

<string name="{f1}">{f2}</string>

put this in template section provided

website also displays the desired converted output file

Cheju answered 17/12, 2020 at 13:15 Comment(2)
This works for me.Herminahermine
How did you do step 1? (convert strings.xml to .csv)?Prefab
N
5
  1. Convert your strings.xml to csv xml-to-csv
  2. Import to Google Sheets
  3. Translate using the formula =GOOGLETRANSLATE(B2, "auto", "de")
  4. Generate output in another column using =CONCATENATE("<string name=",char(34),A2,char(34),">",C2,"</string>") where A2 is the resource_ID and C2 is the translated string
  5. Copy the whole output column and paste inside the <resource>...</resource> tag
Norvin answered 3/12, 2020 at 19:59 Comment(0)
L
4

I would suggest the best tool for android app string localization is the Translations Editor that is inbuilt into Android Studio.

The reason this is a great approach is you are able to make the process both easier for translators and less prone to errors. The XML string files in Android Studio support XLIFF notations that are a standardized method to aid string localization.

By utilizing XLIFF notation in your XML string files you can do the following to help the translators:

  • Provide additional context for declared strings
  • Mark message parts that should not be translated

To use XLIFF in your Android string XML files you need to include the XLIFF 1.2 namespace:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

Here are a few examples of strings from the android localization documentation:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

<!-- Example placeholder for a special unicode symbol -->
<string name="star_rating">Check out our 5
    <xliff:g id="star">\u2605</xliff:g>
</string>

<!-- Example placeholder for a for a URL -->
<string name="app_homeurl">
    Visit us at <xliff:g id="application_homepage">http://my/app/home.html</xliff:g>
</string>

<!-- Example placeholder for a name -->
<string name="prod_name">
    Learn more at <xliff:g id="prod_gamegroup">Game Group</xliff:g>
</string>

<!-- Example placeholder for a literal -->
<string name="promo_message">
    Please use the "<xliff:g id="promotion_code">ABCDEFG</xliff:g>” to get a discount.
</string>

</resources>

To access the Translations Editor in Android Studio, select Open Translations Editor from the context menu for your XML string file (ie. strings.xml) in your project tree (see below).

open translations editor

Lingo answered 6/6, 2015 at 22:53 Comment(6)
I wouldn't call it best. :-) There are two major problems with it: first, you can't customize the font it uses. Second, you can't simply type your translation one after the other, you have to double-click each and every item to get a cursor. For an inherently keyboard-based task, it's a major PITA.Progressist
Three, not two. It doesn't support string arrays (including plurals).Progressist
You can simply copy+paste into Excel the data from Open Translations EditorAncier
doesn't answer the OP's question. He's specifically stated he wants to import/export the strings.xml to .xlsxCalefacient
vikifor, your answer stands alone. You should create a separate post for it as I found it to be the most useful answer here. One additional point for those on MACs..... CMD-C does not work for copy.... you must use CONTROL-C to copy out of Android Studio's translation editor.Pica
The translations editor in Android Studio is crap. It certainly doesn't support any sort of automation. I can paste a =googletranslate() function into sheets or excel and get translations instantly. The built-in tool, when it is not just hanging, does nothing interesting beyond letting me edit the values by hand in a grid instead of in strings.xml files.Stagnant
N
4

As many others pointed out, pressing Ctrl+A in the Translations Editor doesn't work since Android Studio 3.2

I work for a company that outsources translations constantly, so we need to convert android strings to and from xls files. The only solution that worked for us reliably is this fork of the older android-lang-tool. Just build with maven and run the jar.

It exports strings, string-arrays, plurals and their key-values to an xls file. It even exports the comments.

Nammu answered 1/11, 2018 at 11:1 Comment(2)
All the other scripts did not work for me.. This tool works perfectly!Darrick
The first link is deadJoubert
S
1

As Saad Mahmud answered, you can copy from the translation editor (ctrl+a ctrl+c) and then paste into a spreadsheet.

You can copy it back from a spreadsheet to the translation editor by only copying the "default value" and other languages columns, click on the topmost default value and paste (ctrl+v).

It also works with subsets (both subsets of rows and columns), as long as they are next to each other.

Be aware that empty cells in the spreadsheet will not blank out the translation in the editor, it will leave the current untouched.

Also be careful that you haven't added or removed any translation keys since the spreadsheet was created...

Southwest answered 19/7, 2017 at 12:49 Comment(3)
Doesn't work for me. I can press ctrl-v in a text editor and all of the data in teh column from the spreadsheet gets pasted but in Android Studio translation editor, nothing happens.Stagnant
This used to work, but doesn't seem to allow for copying more than one string at a time from the translations editor now.Tantalum
@Tantalum By the way I was able to copy the whole column from excel spreadsheet and then by stand at the topmost column I was able to paste to the whole column rows into translation editor.Cachou
G
1

Export or copy to excel only supported in Windows PC. Still not yet in MAC

Greave answered 15/10, 2018 at 9:19 Comment(0)
L
1

As many others pointed out, you can't simply copy and paste translations from and into Translations Editor since Android Studio 3.2.

The simplest solution I found was saving the Excel file with translations as CSV file and then converting it to XML with regex and vice versa.

To "import" translations the steps:

  1. Save xls/xlsx file with key in first column and translation in second column as CSV file (If you have file with non-ANSI caracters use Google sheets, because Excel doesn't support saving in CSV using utf-8)
  2. Open csv file in text editor which supports "find and replace" with regex (eg. Notepad++)
  3. Open "find and replace" and set regex search
  4. Search ^([^,]*),(.*)$ and replace it with <string name="$1">$2</string>
  5. Copy file to string resources file between tag
  6. Fix possible mistakes

You can use similar method in reverse for "export". Use <string.+name="(.*)".*>(.*)</string> for finding and $1,$2 for replacing. But it only works if every string tag in in one line.

Ladew answered 18/12, 2018 at 12:43 Comment(0)
A
1

I made a script for this in python (Thanks to @Christopher Pickslay's answer for the inspiration) that exports all the locales into a single XLS file: https://github.com/shahimclt/android-strings-export

The basic export works like this:

import os
import xml.etree.ElementTree as ET
import pandas as pd

directory = './app/src/main/res'

string_map = {}

folderNames = []

for root, _, files in os.walk(directory):
    for filename in files:
        if filename == "strings.xml":
            filepath = os.path.join(root, filename)
            folderName = os.path.basename(os.path.dirname(filepath))
            folderNames.append(folderName)
            # Load and parse the strings.xml
            tree = ET.parse(filepath, parser=ET.XMLParser(encoding="UTF-8"))
            root = tree.getroot()
            for string in root.findall("string"):
                # Skip strings marked with translatable="false"
                if string.attrib.get('translatable', 'true') == 'false':
                    continue
                key = string.attrib['name']
                text = string.text
                if key and text:
                    dict = string_map.get(key,{})
                    dict[folderName] = text
                    string_map[key] = dict

header = ["Name"]
for fName in folderNames:
    header.append(fName)

df = pd.DataFrame(columns=header)

rows = []

for key, value in string_map.items():
    value["Name"] = key
    rows.append(value)

df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)

output_file = "strings.xlsx"
df.to_excel(output_file, index=False)

I have also figured out how to import it back in once you've made changes. Check the repo for the full code.

Abstergent answered 20/3 at 9:53 Comment(1)
Thank you very much! I had to figure out how python works a little and download installation files, but my problem was solvedAthodyd
A
0

Most of the answers here seem outdated. I have a strings file that includes emojis, quoted text and line breaks in strings, and this python script worked well to export it to csv, which I was then able to import to Google Sheets to share with my translator. This script also skips strings marked as not translatable.

import csv

# Load and parse the strings.xml
tree = ET.parse('./android/app/src/main/res/values/strings.xml')
root = tree.getroot()

# Open a CSV file for writing
with open('strings.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['Key', 'English text'])  # Write the header row
    
    # Iterate over all string elements in the XML
    for string in root.findall('string'):
        # Skip strings marked with translatable="false"
        if string.attrib.get('translatable', 'true') == 'false':
            continue
        
        key = string.attrib['name']
        text = string.text
        writer.writerow([key, text])  # Write each row to the CSV

print('Conversion completed. Skipped non-translatable strings. Check strings.csv for the output.')
Africah answered 12/3 at 19:8 Comment(0)
P
-1

NOTE: If your res folder doesn't contians strings.xml then Android Studio won't show "Open Editor" in top right corner of the strings.xml file(Open the file). In my case all my string res files are named like strings_feature.xml

To copy/paste from Translations Editor use Android Studio 3.2 Version and below. It allows copy/paste of full column.

Philosophy answered 4/11, 2019 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.