代码简单,直接看注释即可。
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)
原创不易,帅哥美女们取代码的时候帮忙点个赞,能打赏个鸡腿就更好了。