当前位置: 移动技术网 > IT编程>脚本编程>Python > Python读取txt内容写入xls格式excel中的方法

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

2018年11月09日  | 移动技术网IT编程  | 我要评论

施乐5000,正宗茶油价格,msocache是什么文件夹

由于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读取txt内容写入xls格式excel中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网