1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import logging
from pathlib import Path
from typing import Iterator
import pandas as pd
INPUT_DIR = Path(r"C:\test2")
OUTPUT_FILENAME = "Collecte2026.xlsx"
INFO_SHEET_NAME = "Info"
SHEET_NAME_MAX_LENGTH = 31
LOGGER = logging.getLogger(__name__)
def _is_input_excel(file_path: Path) -> bool:
return file_path.suffix.lower() in (".xls", ".xlsx")
def _iter_input_files(input_dir: Path, output_filename: str) -> Iterator[Path]:
for file_path in input_dir.iterdir():
is_output_file = file_path.name == output_filename
if _is_input_excel(file_path) and not is_output_file:
yield file_path
def _write_input_sheet(writer: pd.ExcelWriter, file_path: Path) -> None:
data_frame = pd.read_excel(file_path)
sheet_name = file_path.stem[:SHEET_NAME_MAX_LENGTH]
data_frame.to_excel(writer, sheet_name=sheet_name, index=False)
def _write_info_sheet(writer: pd.ExcelWriter) -> None:
pd.DataFrame(
{"message": ["Aucun fichier Excel exploitable trouve dans le dossier."]},
).to_excel(writer, sheet_name=INFO_SHEET_NAME, index=False)
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(message)s")
INPUT_DIR.mkdir(parents=True, exist_ok=True)
output_file = INPUT_DIR / OUTPUT_FILENAME
written_sheets = 0
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
for file_path in _iter_input_files(INPUT_DIR, OUTPUT_FILENAME):
try:
_write_input_sheet(writer, file_path)
except Exception as error:
LOGGER.error("Erreur avec %s : %s", file_path.name, error)
else:
written_sheets += 1
LOGGER.info("Ajoute : %s", file_path.name)
if written_sheets == 0:
_write_info_sheet(writer)
LOGGER.info("Aucun fichier valide a fusionner, onglet Info cree.")
LOGGER.info("Fusion terminee")
if __name__ == "__main__":
main() |
Partager