python,把txt转为xls,xlsx,使用xlwt, xlsxriter openpyxl三种包

第一种:xlwt

import xlwt
f = open(file_new,encoding="gbk")
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()

第二种:openpyxl

import openpyxl
from openpyxl.utils import get_column_letter
f = open(file_new,encoding="gbk")
wb = openpyxl.Workbook()
ws = wb.active
ws = wb.create_sheet()
ws.title = 'Sheet1'
row = 0
for line in f:
    row +=1
    line = line.strip()
    line = line.split('\t')
    col = 0
for j in range(len(line)):
    col += 1
    ws.cell(column= col,row = row,value=line[j].format(get_column_letter(col)))
wb.save("保存的文件名" )

第三种:xlsxwriter

import xlsxwriter

 wo = xlsxwriter.Workbook("文件名.xlsx")
    sheet = wo.add_worksheet()
    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另起一行
    wo.close()

 

你可能感兴趣的:(python)