Python 我使用 openpyxl 模块编写的脚本,如何优化它?减少执行所需的秒数

Python script That I wrote using openpyxl module, How do I optimize it ? Reduce the amount of seconds it takes to execute

所以我写了一些 python 代码来帮助使用 openpyxl 模块自动化我的办公任务,但问题是我需要优化它的速度/性能。如何提高代码执行速度?

 #measuring time
 import time
 start_time = time.time()

   from openpyxl import Workbook
   from openpyxl.styles import colors
   from openpyxl.styles import Font, Color
   from openpyxl import load_workbook
   from copy import copy
   import datetime as dt

  source_wb = load_workbook("GUARANTEE MASTER FILE (1).xlsx")

  target_wb = load_workbook(r"C:\Users\User1\OneDrive\TEST\GUARANTEE MASTER FILE (2).xlsx")
  ws = target_wb['MASTER FILE']

  for x in range(2, 300):
   for y in range(1, 300):
    if y<15 or (y>17 and y!=20):  
     ws.cell(row=x+72, column=y).value = source_wb['MASTER FILE'].cell(row=x, column=y).value
     ws.cell(row=x+72, column=y).border = copy(source_wb['MASTER FILE'].cell(row=x, column=y).border)
     ws.cell(row=x+72, column=y).fill = copy(source_wb['MASTER FILE'].cell(row=x, column=y).fill)
     ws.cell(row=x+72, column=y).alignment = copy(source_wb['MASTER FILE'].cell(row=x, column=y).alignment)
     ws.cell(row=x+72, column=y).protection = copy(source_wb['MASTER FILE'].cell(row=x, column=y).protection)
    ws.cell(row=x+72, column=y).font = copy(source_wb['MASTER FILE'].cell(row=x, column=y).font)
    ws.cell(row=x+72, column=y).number_format = copy(source_wb['MASTER FILE'].cell(row=x, column=y).number_format)



   target_wb.save(r"C:\Users\User1\OneDrive\TEST\GUARANTEE MASTER FILE (2).xlsx")

#measuring execution time
print("--- %s seconds ---" % (time.time() - start_time))

你可以用变量替换你的 long wb.cell(...)。它会更杂乱,更快。

import time
start_time = time.time()
from openpyxl import load_workbook
from openpyxl.styles import Font, Color
from copy import copy

source_wb = load_workbook("GUARANTEE MASTER FILE (1).xlsx")
ws = source_wb['MASTER FILE']
target_wb = load_workbook("GUARANTEE MASTER FILE (2).xlsx", read_only=True)

for x in range(2, 300):
    for y in range(1, 300):
        if y < 15 or (y>17 and y!=20): 
            cell = ws.cell(row=x+72, column=y)
            cell2 = ws.cell(row=x, column=y)

            cell.value = cell2.value
            cell.border = copy(cell2.border)
            cell.fill = copy(cell2.fill)
            cell.alignment = copy(cell2.alignment)
            cell.protection = copy(cell2.protection)
            cell.font = copy(cell2.font)
            cell.number_format = copy(cell2.number_format)


target_wb.save()
print("--- %s seconds ---" % (time.time() - start_time))

将文件路径设置为相对路径也会使其速度更快一些。我不认为你可以让它比这快得多,因为你的循环槽太多了。