filmov
tv
Python: Group Excel Sheets & Save Them As Separate Workbooks
ะะพะบะฐะทะฐัั ะพะฟะธัะฐะฝะธะต
๐๐๐ฆ๐๐ฅ๐๐ฃ๐ง๐๐ข๐ก
โโโโโโโโโโโโโโโโโโโโโโโโโโ
This tutorial will show you how to group unique Excel sheets and save them as separate Excel Files/Workbooks. The solution is entirely written in Python. No VBA is required. In particular, we will be using the xlwings library.
๐ ๐ฅ๐ฒ๐๐ผ๐๐ฟ๐ฐ๐ฒ๐:
Download the sample files & Python Code:
โ ๐ฆ๐ข๐จ๐ฅ๐๐ ๐๐ข๐๐:
from pathlib import Path # Standard Python Module
import xlwings as xw # pip install xlwings
"""
Iterate over all excel files in a given source directory.
For each worksheet within the excel files create a new workbook.
The name of the new workbook will be equal to the worksheet's name.
If the workbook already exists, append the worksheet to the existing workbook.
"""
SOURCE_DIR = "Month_End_Data"
OUTPUT_DIR = "Output"
excel_files = list(Path(SOURCE_DIR).glob("*.xlsx"))
# Create a dict with the excel file name & path:
# excel_outputs = {'filename1':filepath1,
# 'filename2':filepath2}
output_paths = list(Path(OUTPUT_DIR).glob("*.xlsx"))
excel_outputs = dict(zip(output_names, output_paths))
for excel_file in excel_files:
wb = xw.Book(excel_file)
# Check, if the sheet name already exsits in the output folder (as a separate wb)
# Check, if that wb also contains out sheet (the wb's name)
# If not, we will copy/append the sheet to the existing wb
else:
# Create a new wb and copy the sheet to this new wb
# Afterwards, add the new file & path to the dict 'excel_outputs'
wb_tmp = xw.Book()
# Only quit the excel instance if no other wb is open
else:
๐ง๐ข๐ข๐๐ฆ ๐๐ก๐ ๐ฅ๐๐ฆ๐ข๐จ๐ฅ๐๐๐ฆ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
๐๐ข๐ก๐ก๐๐๐ง ๐ช๐๐ง๐ ๐ ๐
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐๐๐ ๐บ๐ฒ ๐ฎ ๐ฐ๐ผ๐ณ๐ณ๐ฒ๐ฒ?
ะะพะผะผะตะฝัะฐัะธะธ