Skip to content

Instantly share code, notes, and snippets.

@mbarrben
Last active December 10, 2015 22:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbarrben/4500608 to your computer and use it in GitHub Desktop.
Save mbarrben/4500608 to your computer and use it in GitHub Desktop.
Create full directory structure (also lang code suffix) and localised string.xml files for an Android project from an MS Excel file. For those not using xliff or gettext...
------------------------------------------------
| | lang_code_1 | lang_code_2 | ...
------------------------------------------------
| key_1 | translation | translation | ...
------------------------------------------------
| key_2 | translation | translation | ...
. . .
. . .
. . .
---------------------------------------------------------
| | en | es-rES | ...
---------------------------------------------------------
| hello_world | Hello world! | ¡Hola, mundo! | ...
---------------------------------------------------------
| good_bye | Good bye | Adiós | ...
. . .
. . .
. . .
import os
import codecs
import xlrd # Excel library from http://www.python-excel.org/
from optparse import OptionParser
def createAndInitXmlFile(languageCode):
directory = 'res/values-' + languageCode
if not os.path.exists(directory):
os.makedirs(directory)
xmlFile = codecs.open(directory + '/strings.xml', 'w+', encoding='utf-8')
xmlFile.write('<?xml version="1.0" encoding="utf-8" standalone="no"?>\n')
xmlFile.write('<resources>\n')
return file
def endAndCloseXmlFile(xmlFile):
xmlFile.write('</resources>\n')
xmlFile.close()
def getXmlString(key, value):
if key:
return '<string name="%s">%s</string>\n'%(key, value)
else:
if value:
print 'WARNING! EMPTY KEY WITH NOT EMPTY VALUE "%s". EXCEL CAN BE BAD FORMATTED'
return ''
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-f", "--file", help="input file")
(options, args) = parser.parse_args()
sheet = xlrd.open_workbook(options.file).sheet_by_index(0)
for column in range(1, sheet.ncols):
xmlFile = createAndInitXmlFile(sheet.cell_value(rowx=0, colx=column))
for row in range(1, sheet.nrows):
xmlFile.write(getXmlString(sheet.cell_value(rowx=row, colx=0), sheet.cell_value(rowx=row, colx=column)))
endAndCloseXmlFile(xmlFile)
python i18n_xml_from_excel.py -f input_excel_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment