1. 程式人生 > 實用技巧 >python txt裝換成excel

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')