filmov
tv
Python: Copy Data From Multiple Files to Master File | Read/Write Closed Excel Files Using Openpyxl

ะะพะบะฐะทะฐัั ะพะฟะธัะฐะฝะธะต
๐๐๐ฆ๐๐ฅ๐๐ฃ๐ง๐๐ข๐ก
โโโโโโโโโโโโโโโโโโโโโโโโโโ
This tutorial will show you how to read & write closed Excel Files in Python using openpyxl. In particular, we will copy data from multiple Excel files in one Master workbook. After executing the Python script, openpyxl will create a new workbook that combines all the single Excel files.
โ ๐ง๐ถ๐บ๐ฒ๐๐๐ฎ๐บ๐ฝ๐:
00:00 | Problem Statement and Final Outcome
01:26 | Solution Approach
02:30 | Step 1
02:52 | Step 2
04:37 | Step 3
06:43 | Wrap Up
๐ ๐ฅ๐ฒ๐๐ผ๐๐ฟ๐ฐ๐ฒ๐:
Download the Python File & Excel Sample Files here [Google Drive]:
โผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธโผ๏ธ
๐ฉโ๐ป ๐ฃ๐๐๐ต๐ผ๐ป ๐๐ผ๐ฑ๐ฒ:
from pathlib import Path # Standard Python Module
from openpyxl import load_workbook, Workbook # pip install openpyxl
# -- 1.STEP
# Get all excel file paths from given directory
SOURCE_DIR = "Daily_Reports" # e.g. r"C:\Users\Username\Desktop\Sample Files"
excel_files = list(Path(SOURCE_DIR).glob("*.xlsx"))
# -- 2.STEP:
# Iterate over all Excel files from step 1,
# access the worksheet and store the values in a dictionary
# values_excel_files = {['2021-01-01'] : [1,2,3, ..],
# ['2021-01-02'] : [1,2,3, ..]}
values_excel_files = {}
for excel_file in excel_files:
wb = load_workbook(filename=excel_file, read_only=True)
rng = wb["Sheet1"]["B2":"B19"]
rng_values = []
for cells in rng:
for cell in cells:
values_excel_files[report_date] = rng_values
# -- 3.STEP:
# a) Iterate over all worksheets in the master workbook
# b) For each worksheet, iterate over defined Excel range (dates)
# c) If date matches with the key of dictionary (values_excel_files) then insert values & save workbook
clm = "B"
first_row = 3
last_row = len(ws[clm])
rng = ws[f"{clm}{first_row}:{clm}{last_row}"]
for cells in rng:
for cell in cells:
# Iterate over values (list inside the dictionary) and write values to column
๐ง๐ข๐ข๐๐ฆ ๐๐ก๐ ๐ฅ๐๐ฆ๐ข๐จ๐ฅ๐๐๐ฆ
โโโโโโโโโโโโโโโโโโโโโโโโโโ
๐๐ข๐ก๐ก๐๐๐ง ๐ช๐๐ง๐ ๐ ๐
โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐๐๐ ๐บ๐ฒ ๐ฎ ๐ฐ๐ผ๐ณ๐ณ๐ฒ๐ฒ?
ะะพะผะผะตะฝัะฐัะธะธ