python将txt文件转为excel格式

因业务需要,将txt文件转换为excel文件,代码考虑了健壮性,分享一下,代码如下:

使用方法:sh txt2excel.sh file.txt

[cl@master txt2excel]$ cat file.txt

aaaa
bbbb
cccc
dddd
eeee


[cl@master txt2excel]$ cat txt2excel.sh

#!/bin/bash

sourceFile=$1

if [ -z $1 ]
then
    echo "use: sh txt2excel.sh test.txt newfile"
    exit 1
fi

if [ ! -f "${sourceFile}" ];then
    echo "the file of ${sourceFile} doesn't exists!"
    exit 1
fi


outputFile=`echo ${sourceFile}|awk -F'/' '{print $NF}'|awk -F'.' '{print $1}'`
fileDir=${sourceFile%/*}
#第一列增加序号
awk '{print FNR"\t""未知""\t"$0}' ${sourceFile}  > ${sourceFile}_tmp
#第一行增加标题
sed -i '1i id\t客户名称\t流水号' ${sourceFile}_tmp

script_path=`dirname $0`
script_path=`cd $script_path && pwd`

file_path=`dirname $1`
file_path=`cd $file_path && pwd`

python ${script_path}/txt2excel.py ${sourceFile}_tmp ${file_path}/${outputFile}

rm ${sourceFile}_tmp

 [cl@master txt2excel]$ cat txt2excel.py

#!/bin/env python
# -*- encoding: utf-8 -*-
#-------------------------------------------------------------------------------
# Purpose:     txt转换成Excel
# use: python txt2excel.py out.txt ABC
#-------------------------------------------------------------------------------
import datetime
import time
import os
import sys
import xlwt #需要的模块

def txt2xls(filename,xlsname):  #文本转换成xls的函数,filename 表示一个要被转换的txt文本,xlsname 表示转换后的文件名
    print('converting xls ... ')
    f = open(filename)   #打开txt文本进行读取
    x = 0                #在excel开始写的位置(y)
    y = 0                #在excel开始写的位置(x)
    xls=xlwt.Workbook()
    sheet = xls.add_sheet('sheet1',cell_overwrite_ok=True) #生成excel的方法,声明excel
    while True:  #循环,读取文本里面的所有内容
        line = f.readline() #一行一行读取
        if not line:  #如果没有内容,则退出循环
            break
        for i in line.split('\t'):#读取出相应的内容写到x
            item=i.strip()
            sheet.write(x,y,item)
            y += 1 #另起一列
        x += 1 #另起一行
        y = 0  #初始成第一列
    f.close()
    xls.save(xlsname+'.xls') #保存

if __name__ == "__main__":
    filename = sys.argv[1]
    xlsname  = sys.argv[2]
    txt2xls(filename,xlsname)

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值