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

时间:2021-05-22

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

import xlwtimport codecsdef 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中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章