python3使用openpyxl模块操作xlsx文件填充txt

脚本内容为读取xlsx清单文件,插入内容到txt文件:

点击查看代码
# coding: utf-8
import os
import sys
import re
from openpyxl import load_workbook

'''
    优化:仿真处理多个Excel文件,发生产仅处理匹配到的文件
    python autoRelease.py WORKSPACE(路径) BACKUP_BUSSJAR(发生产标识true)
    优化1:临时仿真,删除文件
'''
PATH = sys.argv[1]
if len(sys.argv) == 3:
    if sys.argv[2]:
        BACKUP_BUSSJAR = sys.argv[2]
        print(BACKUP_BUSSJAR)
else:
    BACKUP_BUSSJAR = 'false'
 
listdir = os.listdir(PATH)
xlsx_list = []
RES_FILE = ['release_number.txt', 'release_service.txt', 'release_static.txt', 'release_mobile.txt']
RELEASE = [[], [], [], []]  # number, service, static, mobile

# pattern中变量中的括号无法处理
pattern = r"小尾巴想看雪-\S+-\S+-\w\d{8}-\d{2}\S+.xlsx"
 
# 在path路径下对xlsx文件名进行提取
for item in listdir:
    res = re.findall(pattern, item)
    if res:
        xlsx_list.append(res[0])
		

def dealwith_data(BACKUP_BUSSJAR=None):
    # 进入到路径下
    os.chdir(PATH)

    def single_file(filename):
        # 加载Excel文件
        wb = load_workbook(filename=filename, read_only=True, data_only=True)
        ws1 = wb[wb.sheetnames[0]]  # 问题列表
        row_max = ws1.max_row  # 最大行数
        word = ws1.rows
        for row in word:
            num_value = row[0].value
            ser_value = row[19].value
            sta_value = row[20].value
            mob_value = row[21].value
            if num_value:
                RELEASE[0].append(num_value)
            if ser_value:
                RELEASE[1].append(ser_value)
            if sta_value:
                RELEASE[2].append(sta_value)
            if mob_value:
                RELEASE[3].append(mob_value)

        wb.close()

    # 以上内容为define变量和识别目录
    if BACKUP_BUSSJAR == 'true':
        if len(xlsx_list) == 1:
            xlsx_file = xlsx_list[0]
            print('true',xlsx_file)
            single_file(xlsx_file)
        else:
            print("目录下符合匹配规则的文件仅能为1个文件,当前不满足条件,程序退出")
            sys.exit()
    else:
        if len(xlsx_list) == 0:
            print("目录下符合匹配规则的文件为0个,不满足条件,程序退出")
            sys.exit()
        else:
            for xlsx_file in xlsx_list:
                print('false',xlsx_file)
                single_file(xlsx_file)
                os.remove(xlsx_file)

    # 将Excel文件的缓存数据写入到txt临时文件中
    def write_data(filename, list):
        '''固定操作,将传入的列表内容写入文件汇总'''
        with open(filename, mode='w+', encoding='utf-8') as file:
            for word in list:
                file.write(word)
                file.write('\n')
            file.close()

    write_data(RES_FILE[0], RELEASE[0])
    write_data(RES_FILE[1], RELEASE[1])
    write_data(RES_FILE[2], RELEASE[2])
    write_data(RES_FILE[3], RELEASE[3])
    
    


if __name__ == '__main__':
    dealwith_data(BACKUP_BUSSJAR)

posted @ 2023-07-03 09:58  小尾巴想看雪  阅读(67)  评论(0编辑  收藏  举报