txt文件批量转换为excel文件

把某个文件夹下的所有txt文件全部转换成excel文件


import os
import openpyxl
import codecs
from openpyxl.utils import get_column_letter


def txt_to_xlsx(filename, outfile,  sheetname):
    fr = codecs.open(filename, 'r')
    wb = openpyxl.Workbook()
    ws = wb.active
    ws = wb.create_sheet()
    ws.title = sheetname
    row = 0
    for line in fr:   #按行读取
        row += 1
        line = line.strip()    #移除字符串头尾的空格
        line = line.split(',')      #split()通过指定分隔符对字符串进行切片
        col = 0    #列
        for j in range(len(line)):     #再按列读取
            col += 1
            # print (line[j])
            ws.cell(column=col, row=row, value=line[j].format(get_column_letter(col)))   #遍历列的时候,用字母编号来索引get_column_letter(1) >>> A
    wb.save(outfile)


# 读取xlsx内容
def read_xlsx(filename):
    # 载入文件
    wb = openpyxl.load_workbook(filename)
    # 获取Sheet1工作表
    ws = wb.get_sheet_by_name('Sheet1')
    # 按行读取
    for row in ws.rows:
        for cell in row:
            print(cell.value)
    # 按列读
    for col in ws.columns:
        for cell in col:
            print(cell.value)

if __name__ == '__main__':
    inputdir_path = r' ' #存放txt文件夹路径
    outputdir_path = r' '    #生成excel文件夹路径
    fileList = os.listdir(inputdir_path)
    print(fileList)
    for name in fileList:
        inputfileTxt = os.path.join(inputdir_path,name)
        outfileExcel = os.path.join(outputdir_path,name).replace('.txt', '.xlsx')
        sheetname = name.replace(".txt",'')
        print(sheetname)
        txt_to_xlsx(inputfileTxt, outfileExcel, sheetname)
print(str(len(fileList)) + '个txt文件已转换完毕')

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值