python3使用xlwt模块将txt文件内容写入xls文件

脚本内容如下

点击查看代码
#!/bin/python3
#_*_ coding=utf-8  _*_
#将单个txt文档,转换为xls
import os 
import sys
import xlwt
import glob


style = xlwt.XFStyle()
alignment = xlwt.Alignment()
alignment.vert = 0x01  # 靠左
alignment.horz = 0x01  # 居中
alignment.wrap = 1  # 自动换行
style.alignment = alignment
#txt file to exchange to excel file
def getline(filepath,xlspath):
    #获取所有txt文档
    filelist = glob.glob("{0}".format(filepath))

    try:
        #create new excel file type xls
        xls = xlwt.Workbook()
        for file_ob in filelist:
            #sheet_name = os.path.basename(file_ob).decode("utf-8")
            sheet_name = os.path.basename(file_ob)
            sheet = xls.add_sheet(sheet_name,cell_overwrite_ok=True)
            #txt write to xls
            f = open(file_ob, encoding='utf-8')
            sheet.write(0,0,'时间')
            sheet.write(0,1,'错误信息')
            sheet.write(0,2,'脚本名称',style)
            sheet.write(0,3,'处理进度')
            x = 1
            while True:
                line = f.readline()
                if not line:
                    break
                for i in range(len(line.split(","))):
                    data = str(line.split(",")[i]).replace("\n","")
                    #x横坐标,i纵坐标,data内容
                    #print(x,i,data)
                    sheet.write(x,i,data,style)
                x += 1
            sheet.col(0).width=190*25
            sheet.col(1).width=390*25
            sheet.col(2).width=1000*25
            sheet.col(3).width=190*25
            f.close()
            xls.save(xlspath)
    except:
        raise

if __name__ == "__main__":
    # #txt save path
    # filepath = sys.argv[1]
    # #excel file path/name
    # xlspath = sys.argv[2]
    # getline(filepath,xlspath)
    filepath = 'infomations.txt'
    xlspath = '20230410.xls'
    getline(filepath, xlspath)

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