安装Python2及使用xlrd将Excel自动生成多语言
2023-06-14 本文已影响0人
独孤流
# 1、安装辅助环境
brew install pyenv
# 2、安装python
pyenv install 2.7.18
# 3、设置全局默认 pyenv global 2.7.18
pyenv global 2.7.18
# 4、将python配置到配置环境里
# 在 ~/.zshrc里添加一行
export PATH="$HOME/.pyenv/versions/2.7.18/bin:$PATH"
# 让配置生效
source ~/.zshrc
# 查看版本
python --version
参考:
https://github.com/CatchZeng/Localizable.strings2Excel
安装支持解析xlsx
sudo pip install pyExcelerator
# sudo pip install xlrd
sudo pip install xlrd==1.2.0
xlrd.biffh.XLRDError: Excel xlsx file; not supported
参考:在升级 xlrd 2.0.1 之后不支持 xlsx 的应对方法
sudo pip uninstall xlrd
sudo pip install xlrd==1.2.0
1、下载github:https://github.com/CatchZeng/Localizable.strings2Excel
2、创建python文件如下:xlsx2string.py
# -*- coding:utf-8 -*-
from XlsFileUtil import XlsFileUtil
import os
"""
解析表头为文件夹
"""
def readName(folderPath, val):
name = val.split("(")[1]
name = name.split(")")[0]
langFolderPath = ""
if folderPath.endswith("/"):
langFolderPath = folderPath + name + ".lproj"
else:
langFolderPath = folderPath + "/" + name + ".lproj"
print "colName:%s foldName:%s path:%s" % (val, name, langFolderPath)
# 如果文件夹不存在,则生成
if not os.path.exists(langFolderPath):
os.makedirs(langFolderPath)
filePath = langFolderPath + "/Localizable.strings"
return filePath
"""
解析每一个列文多语言文件
"""
def readCols(targetDir, sheet, colIndex):
# 读取每一行
iosFileManager = None
for rowIndex, row in enumerate(sheet.get_rows()):
if rowIndex == 0:
LocalizablePath = readName(targetDir, row[colIndex].value)
if os.path.exists(LocalizablePath):
#删除文件,path为文件路径
os.remove(LocalizablePath)
# 开启读文件
iosFileManager = open(LocalizablePath, "wb")
else:
strKey = row[1].value
strVal = row[colIndex].value
print "strKey:%s strVal:%s" % (strKey, strVal)
if(not strKey):
# 没有key的行为注释行
moduleName = row[0].value
content = "\n// " + moduleName + "\n"
iosFileManager.write(content)
else:
# 内容行
content = "\"" + strKey + "\" " + "= " + "\"" + strVal + "\";\n"
iosFileManager.write(content)
# 保存关闭
iosFileManager.close()
print "end converting"
def startConvert(xlsxPath, targetDir):
print "Start converting"
if xlsxPath is None:
print "xls files directory can not be empty! try -h for help."
return
if targetDir is None:
print "Target file directory can not be empty! try -h for help."
return
# 解析xls
xlsFileUtil = XlsFileUtil(xlsxPath)
# 读取所有tab
sheet = xlsFileUtil.getAllTables()[0]
colCount = sheet.ncols
print "colCount: %d" % (colCount)
for colIndex in range(2, colCount):
print "colIndex: %d" % (colCount)
readCols(targetDir, sheet, colIndex)
print "end converting"
def main():
# 解析参数
xlsxPath = "examples/helloi18n.xlsx"
targetDir = "examples/output/ios/i18n"
# 开始转换
startConvert(xlsxPath, targetDir)
# python python/xlsx2string.py
main()
3、准备Excel文件
image.png
4、执行文件
image.png