idcard_monthly.py 1.84 KB
import os
import datetime
from calendar import monthrange
from openpyxl import Workbook, load_workbook
from django.core.management import BaseCommand
from settings import conf
from common.mixins import LoggerMixin


class Command(BaseCommand, LoggerMixin):

    def __init__(self):
        super().__init__()
        self.dirs = ('AFC', 'HIL')

    def handle(self, *args, **kwargs):
        now_time = datetime.datetime.now()
        end_day_in_mouth = now_time.replace(day=1)
        pre_mouth = end_day_in_mouth - datetime.timedelta(days=1)

        for target_dir in self.dirs:
            if target_dir == 'AFC':
                excel_dir = conf.IC_REPORT_AFC
            else:
                excel_dir = conf.IC_REPORT_HIL
            if not os.path.exists(excel_dir):
                print('excel dir not exists: {0}'.format(excel_dir))
                return

            monthly_wb = Workbook()

            for d in range(1, monthrange(pre_mouth.year, pre_mouth.month)[1] + 1):
                date_str = '{:04d}-{:02d}-{:02d}'.format(pre_mouth.year, pre_mouth.month, d)
                daily_excel_path = os.path.join(excel_dir, 'idcard_{0}.xlsx'.format(date_str))
                if not os.path.exists(daily_excel_path):
                    print('daily excel path not exists: {0}'.format(daily_excel_path))
                    continue

                monthly_ws = monthly_wb.create_sheet(date_str)
                daily_wb = load_workbook(daily_excel_path)
                daily_ws = daily_wb.get_sheet_by_name('身份证')
                for row in daily_ws.iter_rows(min_row=1, values_only=True):
                    monthly_ws.append(row)

            monthly_excel_path = os.path.join(excel_dir, 'idcard_{0}.xlsx'.format(pre_mouth.strftime('%Y-%m')))
            monthly_wb.remove(monthly_wb.get_sheet_by_name('Sheet'))
            monthly_wb.save(monthly_excel_path)