问题
Quickly setting values and colors of a large number of Excel cells using win32com
I have to calculate the values and set back ground colors of a large number of excel cells. In practice the value of each cell is calculated from information in a database. The color of the cell is set in accordance with HOW that data was calculated. i.e. which bits of the database were used to calculate the value. There will be values that are the same but where calculated via different methods. The background of the cell will be colored to reflect the method used.
The worksheets are actually 120 X 80 but I made my example 12 X 8 to be alittle more manageable.
Simply iterating through each row / column works but it is VERY slow. If the worksheet is visible is take 3-4 minutes. With the worksheet minimized it goes a little faster maybe 1-2 minutes. There are 13 worksheets that need this data. So we are talking up to an hour to update. ( I am talkling about all 9600 cells ... not the 96 in my example )
Without the color information I can set the whole range in one ( or a couple of chunks and it goes very quick.
Is there a method to set a large number of individual cell background colors all at once. Like I can set the Values all at once.
from win32com.client import Dispatch
import random
def CalcCellValue(row,col):
value = random.randint(1,101)
color = random.randint(0,3)
return value , color
excel = Dispatch('Excel.Application')
wb = excel.Workbooks('book1.xlsx')
ws = wb.Worksheets("Sheet1")
Clr = [0xff00ff,0x00ff00,0xffff00,0x00ffff]
#The slow way 3-4 minutes / sheet
for row in range(12):
for col in range(8):
value, color = CalcCellValue(row,col)
ws.Cells(row+1,col+1).Value = value
ws.Cells(row+1,col+1).Interior.color = Clr[color]
#Fast way less than a second but no color information
celldata=[]
for row in range(12):
tmprow=[]
for col in range(8):
value,color = CalcCellValue(row,col)
tmprow.append(value)
celldata.append(tmprow)
ws.Range("A1:H12").Value = celldata
来源:https://stackoverflow.com/questions/54639467/setting-the-color-of-a-large-number-of-excel-cells-quickly