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

yipeiwu_com6年前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读取txt内容写入xls格式excel中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python hmac模块使用实例解析

这篇文章主要介绍了Python hmac模块使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 hmac模块的作用: 用于验证...

python实现在多维数组中挑选符合条件的全部元素

python实现在多维数组中挑选符合条件的全部元素

问题产生:今天在编写神经网络的Cluster作业时,需要根据根据数据标签用不同的颜色画出数据的分布情况,由此学习到了这种高效的方法。 传统思路:用for循环来挑选符合条件的元素,这样十分...

python在Windows8下获取本机ip地址的方法

本文实例讲述了python在Windows8下获取本机ip地址的方法。分享给大家供大家参考。具体实现方法如下: import socket hostname = socket.ge...

python获取目录下所有文件的方法

本文实例讲述了python获取目录下所有文件的方法。分享给大家供大家参考。具体分析如下: os.walk() 函数声明:walk(top,topdown=True,onerror=Non...

使用python绘制二元函数图像的实例

废话少说,直接上代码: #coding:utf-8 import numpy as np import matplotlib.pyplot as plt from mpl_toolk...