美文网首页
安装Python3及使用openpyxl和xlrd将Excel自

安装Python3及使用openpyxl和xlrd将Excel自

作者: 独孤流 | 来源:发表于2023-07-21 00:46 被阅读0次

参考:
https://openpyxl.readthedocs.io/en/stable/api/openpyxl.workbook.workbook.html?highlight=sheetnames#openpyxl.workbook.workbook.Workbook.sheetnames

安装环境:

pip3 install openpyxl
pip3 install xlrd
一、使用openpyxl解析Excel
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import openpyxl
import xlrd

# 读取xlsx
wk = openpyxl.load_workbook(excelFilePath)
# 读取所有sheet的名字
sheetNames = wk.sheetnames
# 读取所有sheet
tables = wk.tables
# 所有table的数量
len(ws.tables)
# 遍历所有sheet
for table in wk.tables.values():
  print(table)
# 读取指定sheet
sheet = wk[sheetName]
# 读取sheet的行数
rowCount = sheet.max_row
# 读取最大列数
rowCount = sheet.max_column
# 读取指定行指定列的值, 索引值是从1开始,跟一般的索引从0开始不一样
sheet.cell(rowIndex, colIndex).value
二、python3 将数组或字典转换为json文件
import json
# 将内容转换为json
demoList = [{"name":"x"},{"name":"y"}]
jsonPath = "xxx/demo.json"
with open(jsonPath, 'w') as file_object:
        json.dump(demoList, file_object, ensure_ascii=False)
三、python3 将文本写入文件
filePath = "xxx/test.text"
fileWriter = open(filePath, "wb")
# 构造文本
content = "\"name\"=\"aaa\";\n"
# 将文本写入
fileWriter.write(content.encode())
# 关闭流
 fileWriter.close()
四、python3 读取文本文件
filePath = "xxx/test.txt"
f = open(filePath)
for index, line in enumerate(f):
    if line != None and len(line) != "0" and "=" in line:
        kvList = line.split("=")
        keyStr = kvList[0].strip().split("\"")[1]
        valStr = kvList[1].strip().split("\"")[1]
       # print("keyStr: %s valStr: %s", keyStr, valStr)
           
五、python3 解析字符串里的指定内容
import re
lineStr = "hello name=234"
# 找出hello与=之间的内容
regx = r'hello(.+?)='
matchs = re.findall(regx, lineStr)
if matchs:
        for item in matchs:
            print(item)

完整内容

# -*- coding:utf-8 -*-

import openpyxl
import os


"""
解析每一个列文多语言文件
"""
def readColData(targetDir, sheet, colIndex):
     # 读取每一行
    iosFileManager = None
    # 行数、列数
    rowCount = sheet.max_row
    # 读取第一行
    languageName = languageName = sheet.cell(0+1,colIndex+1).value
    if languageName == None or len(languageName) == "0":
        return
    languageName = languageName.split("(")[1]
    languageName = languageName.split(")")[0]
    LocalizablePath = os.path.join(targetDir, languageName + ".lproj/Localizable.strings")
    if os.path.exists(LocalizablePath):
        #删除文件,path为文件路径
        os.remove(LocalizablePath)
    # 开启读文件
    iosFileManager = open(LocalizablePath, "wb")

    # 读取数据,从第二行读起,第一行是标题
    for rowIndex in range(1, rowCount):
        # 模块名称:第一列
        moduleName = sheet.cell(rowIndex+1,1+1).value
        # key:固定第一列为key
        keyStr = sheet.cell(rowIndex+1,1+1).value
        # value
        valStr = sheet.cell(rowIndex+1,colIndex+1).value

        if(not keyStr):
            # 没有key的行为注释行
            moduleName = sheet.cell(rowIndex+1,0+1).value
            content = "\n// " + moduleName + "\n"
            iosFileManager.write(content.encode())
        else:
            # 内容行
            content = "\"" + keyStr + "\" " + "= " + "\"" + valStr + "\";\n"
            iosFileManager.write(content.encode())
    # 保存关闭
    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

    # 读取xlsx
    wk = openpyxl.load_workbook(xlsxPath)
    
    # 读取所有tab
    sheet = wk.tables.values()[0]
    colCount = sheet.max_column
    print ("colCount: %d" % (colCount))
    # 第一列为模块名,第二列为key,第三列才是翻译的value
    for colIndex in range(2, colCount):
        print ("colIndex: %d" % (colCount))
        readColData(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()

相关文章

网友评论

      本文标题:安装Python3及使用openpyxl和xlrd将Excel自

      本文链接:https://www.haomeiwen.com/subject/vcttpdtx.html