Dec-11-2019, 11:02 PM
Hello all,
I am new to the forum and python I am seeking some assistance as I have searched and am not able to find the answer I need. What I am doing is coping a certain column and pasting it into another workbook right now I am specifying how many rows to copy and paste as you can see below in copyrange and pasterange. Is there a way in python to copy and paste based on the amount of rows with data? Ex: column A has data from A2:A10 but next weeks file has data from A2:A14 I have my code below I am using to copy and paste. Any help is appreciated!
I am new to the forum and python I am seeking some assistance as I have searched and am not able to find the answer I need. What I am doing is coping a certain column and pasting it into another workbook right now I am specifying how many rows to copy and paste as you can see below in copyrange and pasterange. Is there a way in python to copy and paste based on the amount of rows with data? Ex: column A has data from A2:A10 but next weeks file has data from A2:A14 I have my code below I am using to copy and paste. Any help is appreciated!
# File to be copied wb = openpyxl.load_workbook( "C:/Users/u678153/Desktop/Account_Detail.100219-added MI_210 vFINAL.xlsx") # Add file name sheet = wb["Sheet1"] # Add Sheet name # File to be pasted into template = openpyxl.load_workbook("C:/Users/u678153/Desktop/07_19 ITS Backup current.xlsx") # Add file name temp_sheet = template["Download"] # Add Sheet name # Copy range of cells as a nested list # Takes: start cell, end cell, and sheet you want to copy from. def copyRange(startCol, startRow, endCol, endRow, sheet): rangeSelected = [] # Loops through selected Rows for i in range(startRow, endRow + 1, 1): # Appends the row to a RowSelected list rowSelected = [] for j in range(startCol, endCol + 1, 1): rowSelected.append(sheet.cell(row=i, column=j).value) # Adds the RowSelected List and nests inside the rangeSelected rangeSelected.append(rowSelected) return rangeSelected # Paste range # Paste data from copyRange into template sheet def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData): countRow = 0 for i in range(startRow, endRow + 1, 1): countCol = 0 for j in range(startCol, endCol + 1, 1): sheetReceiving.cell(row=i, column=j).value = copiedData[countRow][countCol] countCol += 1 countRow += 1 print("Processing...") selectedRange = copyRange(6, 3, 6, 26884, sheet) # Change the 4 number values pasteRange(1, 3, 1, 26884, temp_sheet, selectedRange) # You can save the template as another file to create a new file here too.s template.save("C:/Users/u678153/Desktop/07_19 ITS Backup current.xlsx") print("Range copied and pasted!")