Community Spring Cleaning week is here! Join your fellow Maveryx in digging through your old posts and marking comments on them as solved. Learn more here!
Free Trial

Base de Connaissance

Apprenez auprès des experts.
TIPS de la semaine

Chaque semaine, découvrez de nouvelles astuces et bonnes pratiques pour devenir un expert !

Voir l'index

Extraire la couleur des cellules d'une feuille Excel

WilliamR
Alteryx
Alteryx
Créé

Après plusieurs questions posées autour de ce sujet, voici un rapide tutorial pour extraire les couleurs de fonds des cellules d'un classeur Excel.

 

Cette fonctionnalité n'étant pas disponible nativement dans Designer, nous utiliserons un peu de code Python pour cette opération.

 

Pourquoi vouloir extraire la couleur de fond des cellules d'une feuille Excel ?

 

Tout simplement car il s'agit bien souvent d'une information importante, au même titre que la valeur contenue dans la cellule.

 

Nous utilisons ici la librairie openpyxl de Python. Pour installer cette librairie (non contenue par défaut), il faut suivre la procédure écrite disponible ici.

 

Visuel du fichier Excel d'exemple et du workflow :

WilliamR_1-1576768084707.png

 

Voici le code:

from ayx import Alteryx
import pandas as pd
import numpy as np
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl import styles


#Load the data from Alteryx WF (Excel Path)
df=Alteryx.read("#1")

# Load the Excel sheet
excelfile = df.get_value(0,"ExcelFile")
wb = load_workbook(filename=excelfile)

#Load the active sheet, if needed load another sheet based on the name 
#(https://openpyxl.readthedocs.io/en/stable/tutorial.html)
ws = wb.active

#Get row and column count
row_count = ws.max_row
col_count = ws.max_column

#Create the array to store the cell color
result_array = np.full((row_count,col_count),'', dtype=object)

#Initialize some variables
i=0
j=0

#Iterate through worksheet and print cell contents in hex
#If needed convert it to RGB inside python or into Alteryx with a formula
for row in ws.iter_rows():
    for cell in row:
        result_array[i,j]=cell.fill.start_color.index
        j+=1
        if(j==10):j=0
    i+=1 
    
#Create the result dataframe to pass to Alteryx        
df = pd.DataFrame(result_array)

#Send the dataframe   
Alteryx.write(df,1)

 

Ne pas oublier de positionner le fichier d'exemple "Test.xlsx" dans un réperoire et de modifier le chemin dans l'outil input data.

 

Ce code peut ensuite être personalisé pour extraire la fonte, les valeurs des cellules,...

 

Pièces jointes
Commentaires
abell_dt
Météore

I get this error below, do you know why? It has something to do with this line of code: "excelfile = df.get_value(0,"ExcelFile")
wb = load_workbook(filename=excelfile)
"

 

 

--------------------------------------------------------------------------------------

 

Error: Python (37): ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
c:\program files\alteryx\bin\miniconda3\pythontool_venv\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'ExcelFile'
During handling of the above exception, another exception occurred:
KeyError                                  Traceback (most recent call last)
<ipython-input-2-9e139ce14ee5> in <module>
     11
     12 # Load the Excel sheet
---> 13 excelfile = df.get_value(0,"ExcelFile")
     14 wb = load_workbook(filename=excelfile)
     15
c:\program files\alteryx\bin\miniconda3\pythontool_venv\lib\site-packages\pandas\core\frame.py in get_value(self, index, col, takeable)
   2757                       ".at[] or .iat[] accessors instead", FutureWarning,
   2758                       stacklevel=2)
-> 2759         return self._get_value(index, col, takeable=takeable)
   2760
   2761     def _get_value(self, index, col, takeable=False):
c:\program files\alteryx\bin\miniconda3\pythontool_venv\lib\site-packages\pandas\core\frame.py in _get_value(self, index, col, takeable)
   2765             return com.maybe_box_datetimelike(series._values[index])
   2766
-> 2767         series = self._get_item_cache(col)
   2768         engine = self.index._engine
   2769
c:\program files\alteryx\bin\miniconda3\pythontool_venv\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   3059         res = cache.get(item)
   3060         if res is None:
-> 3061             values = self._data.get(item)
   3062             res = self._box_item_values(item, values)
   3063             cache[item] = res
c:\program files\alteryx\bin\miniconda3\pythontool_venv\lib\site-packages\pandas\core\internals\managers.py in get(self, item, fastpath)
    939
    940             if not isna(item):
--> 941                 loc = self.items.get_loc(item)
    942             else:
    943                 indexer = np.arange(len(self.items))[isna(self.items)]
c:\program files\alteryx\bin\miniconda3\pythontool_venv\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2657                 return self._engine.get_loc(key)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2661         if indexer.ndim > 1 or indexer.size > 1:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'ExcelFile'
WilliamR
Alteryx
Alteryx

Hello @abell_dt,

Is your field containing the path to the excel file named "ExcelFile"?

 

WilliamR_0-1581080089445.png

 

Regards.

StephV
Alteryx Alumni (Retired)

Merci pour ta question @abell_dt ! Je suis sûre qu’elle aidera d’autres utilisateurs.

 

Comme ce forum est en langue française, je t'invite à écrire de préférence en français. Si tu préfères l’anglais, aucun problème, tu peux poster ta question sur le Forum anglais.

 

Merci à toi !

 

PS : Si la réponse de @WilliamR t'a aidé, n'hésites pas à l'"Accepter comme solution".

dgarmor
Météore

I am running into the error below.  All seems to be correct with the file name, the file and the text file contents.  Can you give me any insight?

 

dgarmor_0-1622648383419.png

 

Any assistance greatly appreciated

contributeurs
Étiquettes