python将多个txt文档转为一个excel中的多个sheet

安装工具:

          apt install -y python-pip

          pip install openpyxl

方法一:

# cat test.py
import os,sys,openpyxl
from openpyxl import Workbook

#os.chdir('C:/Users/IsBean/Desktop')
wb = Workbook()
outputfile=sys.argv[-1]


def write_excel(txt_name, sheet):
    f1 = open(txt_name, 'r')
    lines = f1.readlines()
    for line in lines:
        split_line = line.split('\t')
        sheet.append(split_line)
for inputfile in sys.argv[1:-1]:
    sheetName=inputfile
    sheet = wb.create_sheet(sheetName)
    write_excel(inputfile, sheet)
    wb.save(outputfile)
wb1 = openpyxl.load_workbook(outputfile)
del wb1['Sheet']   #删掉多余的Sheet空表页表
wb1.save(outputfile)
 

执行: python test.py xian1.txt xian2.txt xian3.txt xian.xlsx

python2版本的,python3不适用

方法二:自己自定文件名,遍历

root@tian-1:/tmp# cat test.py 
# -*- encoding: utf-8 -*-
import os,sys,openpyxl
from openpyxl import Workbook

wb = Workbook()
dirname=raw_input('请输入存放txt的目录名:')
outputfile=raw_input('请输入要写入的excel名:')
alltxt=os.listdir(dirname)

def write_excel(txt_name, sheet):
    f1 = open(txt_name, 'r')
    lines = f1.readlines()
    for line in lines:
        split_line = line.split('\t')
        sheet.append(split_line)
for inputfile in alltxt:
    sheetName=inputfile
    sheet = wb.create_sheet(sheetName)
    write_excel(inputfile, sheet)
    wb.save(outputfile)
wb1 = openpyxl.load_workbook(outputfile)
del wb1['Sheet']
wb1.save(outputfile)
 

执行:/tmp/a下存放了所有要转换的txt文档

~#cd /tmp

/tmp# python test.py 
请输入存放txt的目录名:a
请输入要写入的excel名:xian.xlsx
 

引用原文:

https://blog.csdn.net/weixin_38987362/article/details/81303865

https://juejin.im/entry/5b3b2c7d6fb9a04fe820c5a3

 

 

你可能感兴趣的:(编程,python,excel,txt,openpyxl)