Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Automated Work Log Tracker with Excel Output in Python

Tech Apr 28 34

1. Main Entry Script (work_log.py)

This script collects user input for a daily work log, validates it through confirmation, and delegates processing to a helper module.

log_date = input('Enter log date (e.g., 20240808): ')
tasks = input('Describe today\'s work: ')
hours = input('Work duration (hours): ')
overtime = input('Overtime? (yes/no): ')

confirm = input('Confirm entries are correct? (y/n): ')
while confirm != 'y':
    log_date = input('Enter log date: ')
    tasks = input('Describe today\'s work: ')
    hours = input('Work duration (hours): ')
    overtime = input('Overtime? (yes/no): ')
    confirm = input('Confirm entries are correct? (y/n): ')

import log_processor
log_processor.generate_log_entry(log_date, tasks, hours, overtime)

2. Log Processing Module (log_processor.py)

This module computes the weekday from the provided date string and structures the data for Excel export.

from datetime import datetime
from excel_handler import ExcelWriter

def generate_log_entry(date_str, work_desc, duration, is_overtime):
    def determine_weekday(date_input):
        parsed_date = datetime.strptime(date_input, "%Y%m%d")
        weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        return weekdays[parsed_date.weekday()]

    weekday_name = determine_weekday(date_str)
    month_key = f"{date_str[4:6]}_monthly"

    structured_data = {
        month_key: [date_str, duration, work_desc, weekday_name, is_overtime]
    }

    writer = ExcelWriter()
    writer.append_to_excel(
        data=structured_data,
        folder_name='WorkLogs',
        workbook_name='FieldWorkLog',
        sheet_name='DailyRecords',
        headers=('Date', 'Hours', 'Tasks', 'Weekday', 'Overtime')
    )

3. Excel Handling Utility (excel_handler.py)

A reusable utility to create or update .xls files with new log entries, supporting dynamic sheet creation per month.

import os
import xlwt
import xlrd
from xlutils.copy import copy

class ExcelWriter:
    @staticmethod
    def append_to_excel(data, folder_name, workbook_name, sheet_name, headers):
        base_path = os.path.join(os.getcwd(), folder_name)
        os.makedirs(base_path, exist_ok=True)
        file_path = os.path.join(base_path, f"{workbook_name}.xls")

        # Create new workbook if it doesn't exist
        if not os.path.exists(file_path):
            wb = xlwt.Workbook(encoding='utf-8')
            ws = wb.add_sheet(sheet_name, cell_overwrite_ok=True)
            for col_idx, header in enumerate(headers):
                ws.col(col_idx).width = 2560 * 3
                ws.write(0, col_idx, header)
            wb.save(file_path)

        # Open existing workbook
        existing_wb = xlrd.open_workbook(file_path, formatting_info=True)
        sheet_names = existing_wb.sheet_names()

        writable_wb = copy(existing_wb)
        
        # Add new sheet if not present
        if sheet_name not in sheet_names:
            new_sheet = writable_wb.add_sheet(sheet_name, cell_overwrite_ok=True)
            for col_idx, header in enumerate(headers):
                new_sheet.col(col_idx).width = 2560 * 3
                new_sheet.write(0, col_idx, header)
            next_row = 1
        else:
            target_sheet = existing_wb.sheet_by_name(sheet_name)
            next_row = target_sheet.nrows
            new_sheet = writable_wb.get_sheet(sheet_names.index(sheet_name))

        # Append data
        values = list(data.values())[0]
        for col_idx, value in enumerate(values):
            new_sheet.write(next_row, col_idx, value)

        writable_wb.save(file_path)

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.