In my below program I am trying to update an existing excel template. But when I copy the existing row to a new row(Line 27) it copies the font style and color but wont copy the cell format.
Please advice to copy entire thing from the template. Thank you in advance.
import sys
import openpyxl
def del_row(sheet, row_index):
sheet.delete_rows(row_index)
def copy_source(sheet, i, row_to_copy):
#Get the values from the row to copy
values_to_copy = []
for cell in sheet[row_to_copy]:
values_to_copy.append(cell.value)
# Inset a new row at the next row
sheet.insert_rows(row_to_copy+i)
# Paste the values into the new row
for column, value in enumerate(values_to_copy, start=1):
sheet.cell(row=row_to_copy + i, column=column, value=value)
final_row = row_to_copy + i
return final_row
def write_to_excel(sheet, host_list):
# This for loop is to copy the source row as per the number of hosts
for row_index, host in enumerate(host_list, start= 1):
#copy the source row
next_source_row = copy_source(sheet, row_index, 17)
#Update the copied row with the host
sheet.cell(row=next_source_row, column=2).value = host
sheet.cell(row=next_source_row, column=3).value = "UHST_"+ host.upper()
sheet.cell(row=next_source_row, column=12).value = "UHST_"+ host.upper()
sheet.cell(row=next_source_row, column=19).value = "UHST_"+ host.upper()
#Copy the next source row
next_source_row_2 = copy_source(sheet, row_index, next_source_row + 1)
#Update the copied row with the host
sheet.cell(row=next_source_row_2 , column=2).value = host
return (next_source_row_2 - row_index - 1)
#split the hostnames to individual hostname
def split_hostnames(hostnames):
host_list = hostnames[0].split()
#print(host_list)
return host_list
if __name__ == "__main__":
hostnames = sys.argv[1:]
# Split the hostnames list to individual host
host_list = split_hostnames(hostnames)
# print(len(host_list))
# print(host_list)
# Load the Excel file
file_name= "Template.xltm"
workbook = openpyxl.load_workbook(file_name, keep_vba= True)
# Select the Host sheet
sheet_name="Host"
sheet = workbook[sheet_name]
# Write to excel
result = write_to_excel(sheet, host_list)
del_row(sheet, 17)
del_row(sheet, result)
# Save the modified workbook
workbook.save(file_name)
print(" File has been updated ")