欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python读取txt内容写入xls格式excel中的方法

时间:2022-04-13 09:12:10|栏目:Python代码|点击:

由于xlwt目前只支持xls格式,至于xlsx格式,后面会继续更新

import xlwt
import codecs

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)

 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(' ')
   len_line = len(line)#list中每一行有多少个数,相当于写入excel中的j
   col_excel = start_col
   for j in range(len_line):
    print (line[j])
    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 = 7 #从第7行开始写
 start_col = 3 #从第3列开始写
 inputfile = 'text.txt' #输入文件
 outputExcel = 'excel_result.xls' #输出excel文件
 Txt_to_Excel(inputfile,sheetName,start_row,start_col,outputExcel)el)

上一篇:python中itertools模块使用小结

栏    目:Python代码

下一篇:Python实现为图像添加下雪特效

本文标题:Python读取txt内容写入xls格式excel中的方法

本文地址:http://www.codeinn.net/misctech/199028.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有