python txt装换成excel

工作中,我们需要经常吧一些导出的数据文件,例如sql查出来的结果装换成excel,用文件发送。这次为大家带上python装换excel的脚本

记得先安装wlwt模块,适用版本,python2-3

#coding=utf-8
#!/usr/bin/python
#AUTHOR=ELSON

import xlwt,io,os,sys

"""
运行指令
python name.py  表头文件 分隔符  导入的文件名(可多个)
fx: python srcipt_excel.py head.txt  #  aa.txt  bb.txt cc.txt

cat head.txt (格式='表名,字段1:列宽,字段2:列宽')
第一行:xls保存名字.xls
第二行:sheet1,姓名:20,年龄:10,成绩:10
第三行:sheet2,姓名:20,年龄:10,成绩:10
"""

#表头文件
head = sys.argv[1]
#separator分隔符
separator = sys.argv[2]
#文件名
source_path = sys.argv[3:]
##文件输出路径
execl_path = './'

#条件判断
head_len=len(open(head,'r').readlines()) -1
txt_len=len(source_path)
if head_len != txt_len:
    print('ERROR 表头文件行数 % 不等于  需要转换excel的文件数 %s ,程序退出!' %(head_len,txt_len))
    exit()


xls=xlwt.Workbook(encoding='utf-8')
def setsttle(color=1,blod=False,):   #1=白  #5=黄
    style = xlwt.XFStyle()  # 创建一个样式对象,初始化样式
    #边框
    borders = xlwt.Borders()
    borders.left = 1
    borders.left = xlwt.Borders.THIN
    borders.right = 1
    borders.top = 1
    borders.bottom = 1
    # 定义格式
    style.borders = borders
    # 设置背景颜色
    pattern = xlwt.Pattern()
    # ���置背景颜色的模式
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    # 背景颜色
    pattern.pattern_fore_colour = color
    style.pattern = pattern
    #队列格式
    al = xlwt.Alignment()
    al.horz = 0x02      # 设置水平居中
    al.vert = 0x01      # 设置垂直居中
    style.alignment = al
    #字体
    font = xlwt.Font()
    # 字体类型:比如宋体、仿宋也可以是汉仪瘦金书繁
    #font.name = "仿宋"
    font.bold = blod
    style.font = font
    return style

#写入excel
def write_excel(head,separator,txt_name):
    """
    :param head: 头部文件
    :param separator: 分隔符
    :param txt_name: 装换成excel的txt文件[列表]
    :return: 
    """
    default = setsttle(5,True)
    default2 = setsttle()
    # 表头
    sheet_num = 0
    with open(head, 'r') as f:
        global xls_name
        xls_name = f.readline().strip()
        while True:
            x = 1
            ii = 0
            line = f.readline().strip().replace(' ','').split(',')
            if  not line[0]:
                break
            sheet = xls.add_sheet(line[0])
            for head in line[1:]:
                heads=head.split(':')
                sheet.write(0,ii,heads[0],default)
                sheet.col(ii).width = 265 * int(heads[1])
                ii += 1
            # 表体
            txt_file = io.open(txt_name[sheet_num], mode='r', encoding='UTF-8')
            while True:
                line = txt_file.readline()
                if not line:
                    break
                for i in range(len(line.split(separator))):
                    item = line.split(separator)[i]
                    sheet.write(x, i, item, default2)
                x += 1
            txt_file.close()
            sheet_num += 1
        xls.save(os.path.join(execl_path, xls_name))


#主体写入
if __name__ == '__main__':
    write_excel(head,separator,source_path)
    #保存excel
    print('success')

  

posted @ 2020-07-23 17:30  One只自大猫丶  阅读(271)  评论(0编辑  收藏  举报