转载自:https://blog.csdn.net/levy_cui/article/details/86590614html
接此篇文章:python将txt文件转为excel格式python
上篇文章中将内容写到excel中使用import xlwt包,后来发现文件写入超过65536行的时候就会报错,没法转换成功,ide
xls后缀文件,只支持这么多行,在网上搜索一下,解决方法能够写多个sheet页,但不是我想要的方式,函数
后来后搜索了下,找到了openpyxl包,使用这个包写入数据,文件保存为xlsx格式的,就能够完美解决。ui
一、安装包pip install openpyxlspa
二、再将上篇文章代码(文章开头链接)修改以下,关键点:openpyxl,get_sheet_by_name,sheet.cell(row=x,column=y,value=item), xls.save.net
#!/bin/env python# -*- encoding: utf-8 -*-#-------------------------------------------------------------------------------# Purpose: txt转换成Excel# use: python txt2excel.py out.txt ABC#-------------------------------------------------------------------------------import datetimeimport timeimport osimport sysimport xlwt #须要的模块import openpyxldef txt2xls(filename,xlsname): #文本转换成xls的函数,filename 表示一个要被转换的txt文本,xlsname 表示转换后的文件名print('converting xlsx ... ')f = open(filename) #打开txt文本进行读取x = 1 #在excel开始写的位置(y)y = 1 #在excel开始写的位置(x)xls=openpyxl.Workbook()sheet = xls.get_sheet_by_name('Sheet')while True: #循环,读取文本里面的全部内容line = f.readline() #一行一行读取if not line: #若是没有内容,则退出循环breakfor i in line.split('\t'):#读取出相应的内容写到xitem=i.strip()sheet.cell(row=x,column=y,value=item)y += 1 #另起一列x += 1 #另起一行y = 1 #初始成第一列f.close()xls.save(xlsname+'.xlsx') #保存if __name__ == "__main__":filename = sys.argv[1]xlsname = sys.argv[2]txt2xls(filename,xlsname)
参考:
https://www.cnblogs.com/zeke-python-road/p/8986318.html
https://www.cnblogs.com/li--chao/p/4449502.html
excel