Python将txt文本批量转化为xlsx格式
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
ws.cell(column=col, row=row, value=line[j].format(get_column_letter(col)))
wb.save(outfile)
def read_xlsx(filename):
wb = openpyxl.load_workbook(filename)
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)