Repository navigation
Expand file tree
/
Copy pathRecon_Automation_Code_V1.0.py
More file actions
3570 lines (3051 loc) · 160 KB
/
Copy pathRecon_Automation_Code_V1.0.py
File metadata and controls
3570 lines (3051 loc) · 160 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from openpyxl import load_workbook
import os
import pandas as pd
from openpyxl.styles import Alignment
from openpyxl.styles import Font
from openpyxl.styles import Font, Border, Side
from openpyxl.styles import PatternFill
from openpyxl.worksheet.table import Table, TableStyleInfo
from openpyxl.formula.translate import Translator
from openpyxl.utils import get_column_letter
from openpyxl.styles import NamedStyle
from openpyxl.utils.dataframe import dataframe_to_rows
import win32com.client as client
import shutil
import re
import subprocess
import zipfile
#///////////////////////////////////////////////////////////////////////
# Unzip the file then UnRar the file
def extract_archive(input_folder, output_folder):
if input_folder.endswith(".zip"):
shutil.unpack_archive(input_folder, output_folder, format='zip')
else:
print(f"Unsupported file format: {input_folder}")
# Replace 'your_archive_file.zip' with the actual file path
#input_folder = "[EXTERNAL]_Reconciliation_with_Waybill_January_24,_2024.zip"
# Get the folder path from user input
#path = input("Enter File Path: ").strip() "/Users/nothimofc/Documentsjan 24 kpi 2223"
File_Name = input("Enter file Name: \n")
# Extract the file name from the file path
file_name = os.path.basename(File_Name)
# Extract the month name, date, and year from the file name using regular expressions
match = re.search(r'([a-zA-Z]+)_([0-9]+),_([0-9]+)', file_name)
if match:
month_name = match.group(1)
date = match.group(2)
year = match.group(3)
print(f"Month Name: {month_name}")
print(f"Date: {date}")
print(f"Year: {year}")
else:
print("Date, month, and year not found in file name")
input_folder = os.path.join(os.getcwd(), f"/Users/nothimofc/Documents{File_Name}")
#input_folder = os.path.join(os.getcwd(), path)
output_folder = "Unzip_output_folder"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Extract the main archive
extract_archive(input_folder, output_folder)
# List the contents of the output folder after the first extraction
print(f"Contents of {output_folder}: {os.listdir(output_folder)} \n")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////
def extract_rar_with_winrar(winrar_path, input_folder, output_folder):
# Check if the output folder exists, if not, create it
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Check if the 'UNRAR New' directory exists, if not, create it
unrar_new_folder = os.path.join(output_folder, "RE UNRAR NEW")
if not os.path.exists(unrar_new_folder):
os.makedirs(unrar_new_folder)
# Verify if WinRAR.exe exists at the specified path
if not os.path.isfile(winrar_path):
print(f"Error: WinRAR.exe not found at the specified path: {winrar_path}")
return
for file in os.listdir(input_folder):
if file.endswith(".rar"):
rar_path = os.path.join(input_folder, file)
# Run the WinRAR command to extract the RAR file
subprocess.run([winrar_path, "x", rar_path, unrar_new_folder])
# Iterate over the files in the "UNRAR New" folder for further extraction
for nested_file in os.listdir(unrar_new_folder):
nested_rar_path = os.path.join(unrar_new_folder, nested_file)
if nested_file.endswith(".rar"):
# Run the WinRAR command to extract the nested RAR file
subprocess.run([winrar_path, "x", nested_rar_path, output_folder])
# Replace 'your_winrar_path' and 'Unzip_output_folder' with the actual paths
winrar_path = "C:\\Program Files\\WinRAR\\WinRAR.exe"
input_folder = "Unzip_output_folder"
output_folder = "RE UNRAR NEW"
extract_rar_with_winrar(winrar_path, input_folder, output_folder)
shutil.rmtree('Unzip_output_folder')
input_folder = "RE UNRAR NEW"
output_folder = "Converted Only XLS files"
# Create the output folder if it doesn't exist
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Get a list of all files in the input folder
all_files = os.listdir(input_folder)
# Filter only .xls files
xls_files = [file for file in all_files if file.lower().endswith('.xls')]
# Move each .xls file to the output folder
for xls_file in xls_files:
source_path = os.path.join(input_folder, xls_file)
destination_path = os.path.join(output_folder, xls_file)
shutil.move(source_path, destination_path)
print(f"Moved {len(xls_files)} .xls files to '{output_folder}' folder.")
shutil.rmtree('RE UNRAR NEW')
#///////////////////////////////////////////////////////////////////////
# To Change the extension of Excel From >> .XLS TO >> .XLSX
excel = client.Dispatch("excel.application")
folder_path = os.path.join(os.getcwd(), "Converted Only XLS files")
output_folder = os.path.join(os.getcwd(), "CONVERTED Waybills Chamkani xlsx")
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for file in os.listdir(folder_path):
filename, file_extension = os.path.splitext(file)
file_path = os.path.join(folder_path, file)
try:
# Open the workbook
wb = excel.workbooks.open(file_path)
if wb:
# Save it as xlsx
output_path = os.path.join(output_folder, f"{filename}.xlsx")
wb.SaveAs(output_path, FileFormat=51) # 51 represents xlsx format
wb.Close()
else:
print(f"Error processing {file}: Unable to open workbook.")
except Exception as e:
print(f"Error processing {file}: {e}")
excel.Quit()
shutil.rmtree('Converted Only XLS files')
#////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
##################################
##################################
# FUNCTION DEFINE SPACE #
##################################
##################################
#This Fucntion will take the File Path argument and then it will apply all the First step code to all the Excel Files present in the folders.
def process_excel_file(file_path, output_folder):
# Load the Excel workbook
book = load_workbook(file_path)
# Perform operations on the workbook, for example:
sheet = book.active
book = load_workbook(file_path)
sheet = book.active
sheet_names = book.sheetnames
# Perform operations on the workbook, for example:
filename = file_path.split('/')[-1] # Assuming the file path uses '/' as separator
print("Filename:", filename)
if 'UpLink' in sheet_names and 'Downlink' in sheet_names:
# Get references to the sheets
downlink_sheet = book['Downlink']
uplink_sheet = book['UpLink']
# Iterate through the rows in the Downlink sheet and append to the Uplink sheet
for row in downlink_sheet.iter_rows(min_row=2, values_only=True):
uplink_sheet.append(row)
if 'Downlink' in sheet_names:
book.remove(downlink_sheet) # Remove the Downlink Sheet
print("Downlink Successfully Removed!")
print("Data is successfully added to Uplink!")
# Code for removing Duplicate Trips/rows if any
#////////////////////////////
# Create a set to store unique rows
unique_rows = set()
# List to store rows to be removed
rows_to_remove = []
# Iterate through rows in "UpLink" sheet
for row in uplink_sheet.iter_rows(min_row=2, values_only=True):
if row not in unique_rows:
# Add the row to the set of unique rows
unique_rows.add(row)
else:
# Add the row index to rows_to_remove if it's a duplicate
rows_to_remove.append(row)
# Remove duplicate rows from the "UpLink" sheet
for row in rows_to_remove:
for r in uplink_sheet.rows:
if r[0].value == row[0] and r[1].value == row[1]:
uplink_sheet.delete_rows(r[0].row)
#///////////////////////////
# Delete specified columns
sheet = book.active
sheet.delete_cols(3)
sheet.delete_cols(3)
sheet.delete_cols(4)
sheet.delete_cols(6)
sheet.insert_cols(8) # Insert a column at index 8 (between G and H)
sheet.delete_cols(13)
sheet.delete_cols(13)
sheet.delete_cols(13)
sheet.delete_cols(13)
print("Columns are successfully Removed!")
# Insert a new row at the top
sheet.insert_rows(1)
print("Row on the top is successfully inserted!")
#///////////////////////////////////////////////////////////////
#Entering 'Verified' and 'Waybill' to a cell of Status and Verified From
last_row = uplink_sheet.max_row
# Set the value "Verified" in cell O3
uplink_sheet['O3'] = 'Verified'
uplink_sheet['P3'] = 'Waybill'
# Fill down the value in column O from O3 to the last row
for row in uplink_sheet.iter_rows(min_row=3, max_row=last_row, min_col=15, max_col=15):
for cell in row:
cell.value = 'Verified'
cell.alignment = Alignment(horizontal='center', vertical='center')
# Fill down the value in column P from P3 to the last row
for row in uplink_sheet.iter_rows(min_row=3, max_row=last_row, min_col=16, max_col=16):
for cell in row:
cell.value = 'Waybill'
cell.alignment = Alignment(horizontal='center', vertical='center')
print("'Verified' and 'Waybill' are successfully inserted till the last cell, and filter is applied!")
#///////////////////////////////////////////////////////////////////////
#Adding boarder From U2 to Y12
for row in sheet.iter_rows(min_row=2, max_row=12, min_col=21, max_col=25):
for cell in row:
border_style = Side(style='thin')
cell.border = Border(left=border_style, right=border_style, top=border_style, bottom=border_style)
#Adding Boarder to from U2 to Y12& one cell of Y13
print("table is addes successfully")
#Adding Data to the New Table 13
thin_border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
# Apply the border and fill to Y13 cell
sheet.cell(row=13, column=25).border = thin_border
yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
y13_cell = sheet.cell(row=13, column=25)
y13_cell.border = thin_border
y13_cell.fill = yellow_fill
#Filling color to Table
#///////////////////////////////////////////////////////
# Specify the range of cells (U2 to Y12)
start_cell = sheet['U2']
end_cell = sheet['Y12']
target_range = sheet[start_cell.coordinate:end_cell.coordinate]
# Create a PatternFill object with a green color
fill = PatternFill(start_color='92D050', end_color='92D050', fill_type='solid')
# Apply the PatternFill object to the range of cells
for row in target_range:
for cell in row:
cell.fill = fill
#////////////////////////////////////////////////////////
# Table Data Manopulation Adding Data to Table
sheet.merge_cells('U2:V2') #this will merg the cells
c7 =sheet.cell(row=2, column=21)
c7.value = "12m"
#////////////////////////////////////////////////////
# This will Center the Vlaue in the specify Cell
target_cell = sheet['U2']
alignment = Alignment(horizontal='center', vertical='center')
target_cell.alignment = alignment
#////////////////////////////////////////////////////
c7 =sheet.cell(row=3, column=21)
c7.value = "FWD"
c7 =sheet.cell(row=6, column=21)
c7.value = "RDs"
c7 =sheet.cell(row=7, column=21)
c7.value = "12M"
c7 =sheet.cell(row=10, column=21)
c7.value = "12M"
c7 =sheet.cell(row=3, column=22)
c7.value = "BWD"
sheet.merge_cells('W2:X2') #this will merg the cells
c8 =sheet.cell(row=2, column=23)
c8.value = "18m"
#////////////////////////////////////////////////////
# This will Center the Vlaue in the specify Cell
target_cell = sheet['W2']
alignment = Alignment(horizontal='center', vertical='center')
target_cell.alignment = alignment
#////////////////////////////////////////////////////////
c8 =sheet.cell(row=3, column=23)
print("Data to table is addes successfully")
c8.value = "FWD"
c8 =sheet.cell(row=10, column=23)
c8.value = "18M"
c8 =sheet.cell(row=3, column=24)
c8.value = "BWD"
c8 =sheet.cell(row=7, column=24)
c8.value = "18M"
c9 =sheet.cell(row=3, column=25)
c9.value = "Total"
c9 =sheet.cell(row=8, column=25)
c9.value = "Total"
c9 =sheet.cell(row=11, column=25)
c9.value = "Total"
#///////////////////////////////////////////////////////
#Adding data to First row of sheet and Formating
sheet.merge_cells('O1:P1') #this will merg the cells
sheet.merge_cells('R1:S1')
c1 =sheet.cell(row=1, column=15)
c1.value = "LMKR"
c2 =sheet.cell(row=1, column=18)
c2.value = "KPIs"
c3 =sheet.cell(row=1, column=20)
c3.value = "TPC"
c4 =sheet.cell(row=2, column=15)
c4.value = "Status"
c5 =sheet.cell(row=2, column=16)
c5.value = "Verified From"
c6 =sheet.cell(row=2, column=18)
c6.value = "Headway"
c6 =sheet.cell(row=2, column=19)
c6.value = "Travel Time"
c6 =sheet.cell(row=2, column=8)
c6.value = "Travel Time"
#Making Cell Values BOLD
sheet['A1'].font = Font(b=True)
sheet['T1'].font = Font(b=True)
sheet['R1'].font = Font(b=True)
sheet['O1'].font = Font(b=True)
#////////////////////////////////////////////////////////////////
last_row = sheet.max_row
# Apply the formula to all cells in column H from H3 to the last filled row
for row in range(3, last_row + 1):
sheet[f'H{row}'] = f'=G{row}-F{row}'
# Apply the time format to column H
time_style = NamedStyle(name='time_style', number_format='[hh]:mm')
for row in range(3, last_row + 1):
sheet[f'H{row}'].style = time_style
#////////////////////////////////////////////////////////////////////
print("Data is successfully inserted to the Cells! \n \n")
# Save the changes in the new folder
output_file_path = os.path.join(output_folder, os.path.basename(file_path))
book.save(output_file_path)
# Close the workbook
book.close()
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#This Function will read all the files in the folder then will filter out the excel files from it
#Then it will store the Excel file in a file_path variable that we will be passing to a new functin called process_excel_file()
def process_excel_files_in_folder(input_folder, output_folder):
# List all files in the input folder
files = [f for f in os.listdir(input_folder) if os.path.isfile(os.path.join(input_folder, f))]
# Filter Excel files
excel_files = [f for f in files if f.endswith(".xlsx") or f.endswith(".xls")]
# Process each Excel file
for excel_file in excel_files:
file_path = os.path.join(input_folder, excel_file)
print(f"Processing {excel_file}...")
process_excel_file(file_path, output_folder)
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#These functions are only For Chamkani Routes
# Define functions for each file
# ///////////////////////////////// ROUTES FOR CHAMAKANI ///////////////////////////////////////////////
def dr3a():
# List all files in the input folder
files = [f for f in os.listdir(output_folder_path) if os.path.isfile(os.path.join(output_folder_path, f))]
# Filter Excel files
excel_files = [f for f in files if f.endswith(".xlsx") or f.endswith(".xls")]
# Initialize the variable to store the file name containing 'DR-03A'
dr03a_file = None
# Process each Excel file
for excel_file in excel_files:
file_path = os.path.join(output_folder_path, excel_file)
# Check if the file name contains 'DR-04b'
if 'DR-03A' in excel_file:
dr03a_file = excel_file
print(f"File with 'DR-03A' found: {dr03a_file}")
# Check if a file with 'DR-03A' was found
if dr03a_file:
try:
# Read the Excel file and get the value of cell A2
dr03a_file_path = os.path.join(output_folder_path, dr03a_file)
workbook = load_workbook(dr03a_file_path)
sheet = workbook.active
sheet.title = 'DR-03A'
#Extracting Date From File name using String indexing
print("Filename:", dr03a_file)
date = dr03a_file[25:33]
print(f"Date: {date}") # This will print Date from File name
c = sheet.cell(row=1, column=1)
# Inserting data to the cells
c.value = date # This will add date to the 1st Cell
#////////////////////////////////////////////////////////////////////
# Apply the formula to all THE GREEN cells in column U4 to Y13
# GREEN TABLE DATA FOR DR-03A
# CELL DATA FOR FOR 12M
c8 =sheet.cell(row=8, column=21)
c8.value = "Forward RD DG"
c8 =sheet.cell(row=11, column=21)
c8.value = "Forward RD Kohat Adda"
c8 =sheet.cell(row=8, column=22)
c8.value = "Backward RD DG"
c8 =sheet.cell(row=11, column=22)
c8.value = "Backward RD Kohat Adda"
sheet = workbook.active
sheet.title = 'DR-03A'
sheet['U4'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward",$O:$O,"V*")'
sheet['V4'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward",$O:$O,"V*")'
sheet['U9'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward RD DG",$O:$O,"V*")'
sheet['V9'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward RD DG",$O:$O,"V*")'
sheet['U12'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward RD Kohat Adda",$O:$O,"V*")'
sheet['V12'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward RD Kohat Adda",$O:$O,"V*")'
# CELL DATA FOR FOR 18M
c8 =sheet.cell(row=8, column=23)
c8.value = "Forward"
c8 =sheet.cell(row=11, column=23)
c8.value = "Forward"
c8 =sheet.cell(row=8, column=24)
c8.value = "Backward"
c8 =sheet.cell(row=11, column=24)
c8.value = "Backward"
sheet['W4'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Forward",$O:$O,"V*")'
sheet['X4'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['W9'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['X9'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['W12'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward RD DG",$O:$O,"V*")'
sheet['X12'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward RD DG",$O:$O,"V*")'
#TOTAL
sheet['Y4'] = '=SUM(U4:X4)'
sheet['Y9'] = '=SUM(U9:X9)'
sheet['Y12'] = '=SUM(U12:X12)'
sheet['Y13'] = '=SUM(Y4:Y12)'
# Read data into a pandas DataFrame, skipping the first row (header is in the 2nd row)
data = sheet.iter_rows(values_only=True)
next(data) # Skip the first row
columns = next(data)
# Print the column names
print(columns)
# Convert the remaining rows into a DataFrame
df = pd.DataFrame(data, columns=columns)
L1 = ['Forward', 'Backward', 'Forward RD DG', 'Backward RD DG', 'Forward RD Kohat Adda']
L2 = ['FWD', 'BWD', 'FWD RD DG', 'BWD RD DG', 'FWD RD KOHAT ADDA']
for driving_scheme, sheet_name in zip(L1, L2):
# Filter rows based on the current driving_scheme
filtered_df = df[df['Driving Scheme'].str.strip().eq(driving_scheme)]
# Create a new sheet with the corresponding sheet_name and paste filtered data
new_sheet = workbook.create_sheet(sheet_name)
# Append column names
new_sheet.append(df.columns.tolist())
# Append rows from the filtered DataFrame
for row in dataframe_to_rows(filtered_df, index=False, header=False):
new_sheet.append(row)
# Iterate over each sheet name in L2
start_column = 'R'
end_column = 'Y'
for sheet_name in L2:
# Get the corresponding sheet
sheet = workbook[sheet_name]
# Insert a row at the top (before the existing rows)
sheet.insert_rows(1)
c = sheet.cell(row=1, column=1)
c.value=date #this will add date to 1st Cell
sheet['A1'].font = Font(b=True)
# Calculate the column indexes to delete
start_index = sheet[start_column][0].column
end_index = sheet[end_column][0].column + 1
# Delete columns R to Y
for _ in range(end_index - start_index):
sheet.delete_cols(start_index)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sheet = workbook['BWD']
# Create a named style for the time format
time_style = NamedStyle(name='time_format')
time_style.number_format = '[hh]:mm'
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD RD DG']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['BWD RD DG']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD RD KOHAT ADDA']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
except Exception as e:
print(f"Error reading {dr03a_file}: {e}")
else:
print("No file with 'DR-03A' found. \n")
workbook.save(dr03a_file_path)
print("DR-03A file Code Exicuted And \n Date is added And \n Sheets are added \n")
def dr3b():
# List all files in the input folder
files = [f for f in os.listdir(output_folder_path) if os.path.isfile(os.path.join(output_folder_path, f))]
# Filter Excel files
excel_files = [f for f in files if f.endswith(".xlsx") or f.endswith(".xls")]
# Initialize the variable to store the file name containing 'DR-04B'
dr03b_file = None
# Process each Excel file
for excel_file in excel_files:
file_path = os.path.join(output_folder_path, excel_file)
# Check if the file name contains 'DR-03B'
if 'DR-03B' in excel_file:
dr03b_file = excel_file
print(f"File with 'DR-03B' found: {dr03b_file}")
# Check if a file with 'DR-03B' was found
if dr03b_file:
try:
# Read the Excel file and get the value of cell A2
dr03b_file_path = os.path.join(output_folder_path, dr03b_file)
workbook = load_workbook(dr03b_file_path)
sheet = workbook.active
print("Filename:", dr03b_file)
date = dr03b_file[25:33]
print(f"Date: {date}") # This will print Date from File name
c = sheet.cell(row=1, column=1)
# Inserting data to the cells
c.value = date # This will add date to the 1st Cell
# GREEN TABLE DATA FOR DR-03A
# CELL DATA FOR FOR 12M
c8 =sheet.cell(row=8, column=21)
c8.value = "Forward RD MSS"
c8 =sheet.cell(row=11, column=21)
c8.value = "Forward RD SHP"
c8 =sheet.cell(row=8, column=22)
c8.value = "Backward RD MSS"
c8 =sheet.cell(row=11, column=22)
c8.value = "Backward RD SHP"
sheet['U4'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward",$O:$O,"V*")'
sheet['V4'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward",$O:$O,"V*")'
sheet['U9'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward RD MSS",$O:$O,"V*")'
sheet['V9'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward RD MSS",$O:$O,"V*")'
sheet['U12'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward RD SHP",$O:$O,"V*")'
sheet['V12'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward RD SHP",$O:$O,"V*")'
# CELL DATA FOR FOR 18M
c8 =sheet.cell(row=8, column=23)
c8.value = "Forward"
c8 =sheet.cell(row=11, column=23)
c8.value = "Forward"
c8 =sheet.cell(row=8, column=24)
c8.value = "Backward"
c8 =sheet.cell(row=11, column=24)
c8.value = "Backward"
sheet['W4'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Forward",$O:$O,"V*")'
sheet['X4'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['W9'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['X9'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['W12'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward RD DG",$O:$O,"V*")'
sheet['X12'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward RD DG",$O:$O,"V*")'
#TOTAL
sheet['Y4'] = '=SUM(U4:X4)'
sheet['Y9'] = '=SUM(U9:X9)'
sheet['Y12'] = '=SUM(U12:X12)'
sheet['Y13'] = '=SUM(Y4:Y12)'
sheet = workbook.active
sheet.title = 'DR-03B'
# Read data into a pandas DataFrame, skipping the first row (header is in the 2nd row)
data = sheet.iter_rows(values_only=True)
next(data) # Skip the first row
columns = next(data)
# Print the column names
print(columns)
# Convert the remaining rows into a DataFrame
df = pd.DataFrame(data, columns=columns)
L1 = ['Forward', 'Backward', 'Forward RD MSS', 'Backward RD MSS', 'Forward RD SHP', 'Backward RD SHP']
L2 = ['FWD', 'BWD', 'FWD RD MSS', 'BWD RD MSS', 'FWD RD SHP', 'BWD RD SHP']
for driving_scheme, sheet_name in zip(L1, L2):
# Filter rows based on the current driving_scheme
filtered_df = df[df['Driving Scheme'].str.strip().eq(driving_scheme)]
# Create a new sheet with the corresponding sheet_name and paste filtered data
new_sheet = workbook.create_sheet(sheet_name)
# Append column names
new_sheet.append(df.columns.tolist())
# Append rows from the filtered DataFrame
for row in dataframe_to_rows(filtered_df, index=False, header=False):
new_sheet.append(row)
# Iterate over each sheet name in L2
start_column = 'R'
end_column = 'Y'
for sheet_name in L2:
# Get the corresponding sheet
sheet = workbook[sheet_name]
# Insert a row at the top (before the existing rows)
sheet.insert_rows(1)
c = sheet.cell(row=1, column=1)
c.value=date #this will add date to 1st Cell
sheet['A1'].font = Font(b=True)
# Calculate the column indexes to delete
start_index = sheet[start_column][0].column
end_index = sheet[end_column][0].column + 1
# Delete columns R to Y
for _ in range(end_index - start_index):
sheet.delete_cols(start_index)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sheet = workbook['BWD']
# Create a named style for the time format
time_style = NamedStyle(name='time_format')
time_style.number_format = '[hh]:mm'
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD RD MSS']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['BWD RD MSS']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD RD SHP']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['BWD RD SHP']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
except Exception as e:
print(f"Error reading {dr03b_file}: {e}")
else:
print("No file with 'DR-03B' found. \n")
workbook.save(dr03b_file_path)
print("DR-03B file Code Exicuted And \n Date is added And \n Sheets are added \n")
def dr4b():
# List all files in the input folder
files = [f for f in os.listdir(output_folder_path) if os.path.isfile(os.path.join(output_folder_path, f))]
# Filter Excel files
excel_files = [f for f in files if f.endswith(".xlsx") or f.endswith(".xls")]
# Initialize the variable to store the file name containing 'DR-04B'
dr04b_file = None
# Process each Excel file
for excel_file in excel_files:
file_path = os.path.join(output_folder_path, excel_file)
# Check if the file name contains 'DR-04b'
if 'DR-04B' in excel_file:
dr04b_file = excel_file
print(f"File with 'DR-04B' found: {dr04b_file}")
# Check if a file with 'DR-04B' was found
if dr04b_file:
try:
# Read the Excel file and get the value of cell A2
dr04b_file_path = os.path.join(output_folder_path, dr04b_file)
workbook = load_workbook(dr04b_file_path)
sheet = workbook.active
sheet.title = 'DR-04B'
print("Filename:", dr04b_file)
date = dr04b_file[25:33]
print(f"Date: {date}") # This will print Date from File name
sheet = workbook.active
c = sheet.cell(row=1, column=1)
# Inserting data to the cells
c.value = date # This will add date to the 1st Cell
#/////////////////////////////////
# GREEN TABLE DATA FOR DR-04B
# CELL DATA FOR FOR 12M
c8 =sheet.cell(row=8, column=21)
c8.value = "Forward RD MSS"
c8 =sheet.cell(row=11, column=21)
c8.value = "N/A"
c8 =sheet.cell(row=8, column=22)
c8.value = "Backward RD MSS"
c8 =sheet.cell(row=11, column=22)
c8.value = "N/A"
sheet['U4'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward",$O:$O,"V*")'
sheet['V4'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward",$O:$O,"V*")'
sheet['U9'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Forward RD MSS",$O:$O,"V*")'
sheet['V9'] = '=COUNTIFS($A:$A,"B*",$D:$D,"Backward RD MSS",$O:$O,"V*")'
# CELL DATA FOR FOR 18M
c8 =sheet.cell(row=8, column=23)
c8.value = "Forward"
c8 =sheet.cell(row=11, column=23)
c8.value = "Forward"
c8 =sheet.cell(row=8, column=24)
c8.value = "Backward"
c8 =sheet.cell(row=11, column=24)
c8.value = "Backward"
sheet['W4'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Forward",$O:$O,"V*")'
sheet['X4'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['W9'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['X9'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward",$O:$O,"V*")'
sheet['W12'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward RD SHP",$O:$O,"V*")'
sheet['X12'] = '=COUNTIFS($A:$A,"A*",$D:$D,"Backward RD SHP",$O:$O,"V*")'
#TOTAL
sheet['Y4'] = '=SUM(U4:X4)'
sheet['Y9'] = '=SUM(U9:X9)'
sheet['Y12'] = '=SUM(U12:X12)'
sheet['Y13'] = '=SUM(Y4:Y12)'
sheet = workbook.active
# Read data into a pandas DataFrame, skipping the first row (header is in the 2nd row)
data = sheet.iter_rows(values_only=True)
next(data) # Skip the first row
columns = next(data)
# Print the column names
print(columns)
# Convert the remaining rows into a DataFrame
df = pd.DataFrame(data, columns=columns)
L1 = ['Forward', 'Backward']
L2 = ['FWD', 'BWD']
for driving_scheme, sheet_name in zip(L1, L2):
# Filter rows based on the current driving_scheme
filtered_df = df[df['Driving Scheme'].str.strip().eq(driving_scheme)]
# Create a new sheet with the corresponding sheet_name and paste filtered data
new_sheet = workbook.create_sheet(sheet_name)
# Append column names
new_sheet.append(df.columns.tolist())
# Append rows from the filtered DataFrame
for row in dataframe_to_rows(filtered_df, index=False, header=False):
new_sheet.append(row)
# Iterate over each sheet name in L2
start_column = 'R'
end_column = 'Y'
for sheet_name in L2:
# Get the corresponding sheet
sheet = workbook[sheet_name]
# Insert a row at the top (before the existing rows)
sheet.insert_rows(1)
c = sheet.cell(row=1, column=1)
c.value=date #this will add date to 1st Cell
sheet['A1'].font = Font(b=True)
# Calculate the column indexes to delete
start_index = sheet[start_column][0].column
end_index = sheet[end_column][0].column + 1
# Delete columns R to Y
for _ in range(end_index - start_index):
sheet.delete_cols(start_index)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
sheet = workbook['BWD']
# Create a named style for the time format
time_style = NamedStyle(name='time_format')
time_style.number_format = '[hh]:mm'
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
sheet = workbook['FWD']
# Create a named style for the time format
# Apply the named style to column H
for cell in sheet['H']:
cell.style = time_style
# Get the maximum row number
max_row = sheet.max_row
# Apply the formula to each row in column H from row 3 to the maximum row
for row in range(3, max_row + 1):
cell_g = sheet[f'G{row}']
cell_f = sheet[f'F{row}']
cell_h = sheet[f'H{row}']
cell_h.value = f'={cell_g.coordinate}-{cell_f.coordinate}'
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
except Exception as e: