Python将txt文本批量转化为xlsx格式

Python将txt文本批量转化为xlsx格式

# # -*- encoding: utf-8 -*-
# # -------------------------------------------------------------------------------
# # Purpose:     txt转换成Excel(xlsx格式)
# # Created:     2021-2-20
# # -------------------------------------------------------------------------------
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(',')
        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)))
    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 = txt文件根目录
    outputdir_path = 输出文件路径
    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)

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值