Monday, October 12, 2020

Python and Openpyxl - Read in multiple txt files and store as different worksheets in a single Excel file

If you have some text file and want to combine them into different worksheets of the same Excel file, simply follow the example below using Python:

1. Create some txt files and separate data with tabs:


2. Save the following code as a python file:

import csv
import openpyxl

inputArray = ['a', 'b', 'c']

wb = openpyxl.Workbook()
output_file = 'output.xlsx'

#loop in the reversed order so that the first file is stored as the first sheet.
for item in reversed(inputArray):

    input_file = item+'.txt'
    sheet = wb.create_sheet(item, 0)

    with open(input_file, 'rt') as data:
    reader = csv.reader(data, delimiter='\t')
    for row in reader:
    sheet.append(row)

wb.save(output_file)

Note: install openpyxl using pip or miniconda if required.

3. result:



Reference:

如何使用 Python 程式操作 Excel 試算表 (TechBridge 技術共筆部落格 by kdchang)

No comments:

Post a Comment