Python Forum

Full Version: Loop Excel Range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

This script currently loops through all the excel files in my input dir. How would I make it so I could pick excel files 5-10, or 15-20 to loop through instead of all the files. Sometimes I don't need to loop through them all.


import openpyxl as xl; 
import os

 
input_dir = 'C:/data'
output_dir = os.path.join(input_dir, 'output') 
template = 'C:/data/Template.xlsx'


files = [file for file in os.listdir(input_dir)
         if os.path.isfile(file) and file.endswith('.xlsx')]
  
for file in files:
    input_file =  os.path.join(input_dir, file) # make the full path, so that it does not depend on input_dir and CWD being the same
    wb=xl.load_workbook(input_file)
    ws=wb.worksheets[1]
      
    # Open template
    wb2 = xl.load_workbook(template) 
    ws2 = wb2.worksheets[2] 
     
    # calculate total number of rows and  
    # columns in source excel file 
    mr = ws.max_row 
    mc = ws.max_column 
     
    # copying the cell values from source  
    # excel file to destination excel file 
    for i in range (1, mr + 1): 
        for j in range (1, mc + 1): 
             
    # reading cell value from source excel file 
            c = ws.cell(row = i, column = j) 
    # Cells for source data to pasted inside Template
            ws2.cell(row = i+12, column = j+1).value = c.value 
     
    # saving the destination excel file 

    output_file = os.path.join(output_dir, file)
    wb2.save(output_file)
With no actual example of what the filename would look like all I can advise is the following.
Split the file pathnames to separate out the numbers, convert them from strings to numbers then check they are in the required range.
(Jun-18-2020, 04:38 PM)Yoriz Wrote: [ -> ]With no actual example of what the filename would look like all I can advise is the following.
Split the file pathnames to separate out the numbers, convert them from strings to numbers then check they are in the required range.

Example of the excel files inside the directory
NNB-6a_v1_Nm-Report.xlsx
NNB-6a_v1_T01-Report.xlsx
NNB-6a_v1_T02-Report.xlsx