python txt文件转excel

 代码简单,直接看注释即可。

import xlwt
import codecs
import os.path
import time

def Txt_to_Excel(inputTxt, sheetName, start_row, start_col, outputExcel):
    fr = codecs.open(inputTxt, 'r')
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet(sheetName)
    print(type(fr))
    line_number = 0  # 记录有多少行,相当于写入excel时的i,
    row_excel = start_row
    try:
        for line in fr:
            line_number += 1
            row_excel += 1
            line = line.strip()
            line = line.split('\t')
            len_line = len(line)  # list中每一行有多少个数,相当于写入excel中的j
            col_excel = start_col
            for j in range(len_line):
                if j == 0: continue
                if j == 1 and row_excel != 0: line[j] = line[j][1:len(line[j]) - 1]
                ws.write(row_excel, col_excel, line[j])
                col_excel += 1
                wb.save(outputExcel)
    except:
        print('')


if __name__ == '__main__':
    sheetName = 'Sheet2'  # 需要写入excel中的Sheet2中,可以自己设定
    start_row = -1  # 从第0行开始写
    start_col = 0  # 从第0列开始写
    inputfile = 'E:\\project\\toexcel\\信息转成execl.txt'  # 输入文件
    filename = os.path.dirname(inputfile)
    date = time.strftime("%F")
    outputExcel = filename+r'\\'+date+'.xls'
    Txt_to_Excel(inputfile, sheetName, start_row, start_col, outputExcel)

原创不易,帅哥美女们取代码的时候帮忙点个赞,能打赏个鸡腿就更好了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Besproma_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值