python如何将txt与excel进⾏相互转换(.xls、.xlsx)python 如何将txt与excel 进⾏相互转换(.xls、.xlsx)
Python处理03版xls的excel 需要⽤到xlrd、xlwt来读写,⽽处理07版xlsx的excel需要⽤到openpyxl,⾸先读取txt内容,写⼊xlsx中,然后在读取xlsx中的内容。
python 将txt⽂件转换为excel⽂件(.xls;.xlsx)
# -*- encoding: utf-8 -*-
import xlwt #需要的模块
def txt_xls(filename,xlsname):
"""
:⽂本转换成xls的函数
:param filename txt⽂本⽂件名称、
:param xlsname 表⽰转换后的excel⽂件名
"""
try:
f = open(filename)
xls=xlwt.Workbook()
#⽣成excel的⽅法,声明excel
sheet = xls.add_sheet('sheet1',cell_overwrite_ok=True)
x = 0
while True:
#按⾏循环,读取⽂本⽂件
line = f.readline()
if not line:
break #如果没有内容,则退出循环
for i in range(len(line.split('\t'))):
item=line.split('\t')[i]
sheet.write(x,i,item) #x单元格经度,i 单元格纬度
x += 1 #excel另起⼀⾏
f.close()
xls.save(xlsname) #保存xls⽂件
except:
python怎么读入excelraise
if __name__ == "__main__" :
filename = "G:/"
xlsname = "G:/test.xls"
txt_xls(filename,xlsname)
python 将excel⽂件转换为txt⽂件(.xls;.xlsx)
import xlrd
def strs(row):
"""
:返回⼀⾏数据
"""
try:
values = "";
for i in range(len(row)):
if i == len(row) - 1:
values = values + str(row[i])
else:
#使⽤“,”逗号作为分隔符
values = values + str(row[i]) + ","
return values
except:
raise
def xls_txt(xls_name,txt_name):
"""
:excel⽂件转换为txt⽂件
:
param xls_name excel ⽂件名称
:param txt_name txt ⽂件名称
"""
try:
data = xlrd.open_workbook(xls_name)
sqlfile = open(txt_name, "a")
table = data.sheets()[0] # 表头
nrows = ws # ⾏数
#如果不需跳过表头,则将下⼀⾏中1改为0
for ronum in range(1, nrows):
row = w_values(ronum)
values = strs(row) # 条⽤函数,将⾏数据拼接成字符串
sqlfile.writelines(values) #将字符串写⼊新⽂件
sqlfile.close() # 关闭写⼊的⽂件
except:
pass
if __name__ == '__main__':
xls_name = 'G:/test.xls'
txt_name = 'G:/'
xls_txt(xls_name,txt_name)
Python读取txt内容写⼊xlsx格式的excel中
"""
QQ2737499951
"""
import openpyxl
import codecs
from openpyxl.utils import get_column_letter
def txt_to_xlsx(filename,outfile):
fr = codecs.open(filename,'r')
wb = openpyxl.Workbook()
ws = wb.active
ws = wb.create_sheet()
ws.title = 'Sheet1'
row = 0
for line in fr:
row +=1
line = line.strip()
line = line.split('\t')
col = 0
for j in range(len(line)):
col +=1
#print (line[j])
#读取xlsx内容
def read_xlsx(filename):
#载⼊⽂件
wb = openpyxl.load_workbook(filename)
#获取Sheet1⼯作表
ws = wb.get_sheet_by_name('Sheet1')
#按⾏读取
for row ws:
for cell in row:
print (cell.value)
#按列读
for col lumns:
for cell in col:
print (cell.value)
if __name__=='__main__':
inputfileTxt = ''
outfileExcel = 'text_result.xlsx'
txt_to_xlsx(inputfileTxt,outfileExcel)
read_xlsx(outfileExcel)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论