Convalida dei dati

Tipi ed esecuzione della convalida dei dati

La convalida dei dati è la capacità di impostare regole relative ai dati inseriti in un foglio di lavoro. Ad esempio, utilizzare la convalida per garantire che una colonna denominata DATA contenga solo date, o che un’altra colonna contenga solo numeri. È possibile anche garantire che una colonna denominata DATA contenga solo date entro un determinato intervallo. Con la convalida dei dati è possibile controllare cosa viene inserito nelle celle del foglio di lavoro.

Microsoft Excel supporta diversi tipi di convalida dei dati. Ogni tipo viene utilizzato per controllare quale tipo di dati viene inserito in una cella o in un intervallo di celle. Di seguito, frammenti di codice illustrano come convalidare che:

  • I numeri sono interi, cioè non hanno una parte decimale.
  • I numeri decimali seguono la struttura corretta. L’esempio di codice definisce che un intervallo di celle dovrebbe avere due decimali.
  • I valori sono limitati a un elenco di valori. La convalida dell’elenco definisce un elenco separato di valori che possono essere applicati a una cella o a un intervallo di celle.
  • Le date rientrano in un intervallo specifico.
  • Un’ora è all’interno di un intervallo specifico.
  • Un testo è di una determinata lunghezza di caratteri.

Convalida dei dati con Microsoft Excel

Per creare convalide utilizzando Microsoft Excel:

  1. In un foglio di lavoro, selezionare le celle a cui si desidera applicare la convalida.
  2. Dal menu Dati, seleziona Convalida. Verrà visualizzata la finestra di dialogo di convalida.
  3. Fai clic sulla scheda Impostazioni e inserisci le impostazioni.

Convalida dei dati con la libreria Excel Aspose.Cells per Python

La convalida dei dati è una funzionalità potente per convalidare le informazioni inserite nei fogli di lavoro. Con la convalida dei dati, gli sviluppatori possono fornire agli utenti un elenco di scelte, limitare le voci di dati a un tipo o dimensione specifici, ecc. In Aspose.Cells per Python via .NET, ogni classe Worksheet ha una proprietà validations che rappresenta una collezione di oggetti Validation. Per impostare la convalida, impostare alcune delle proprietà della classe Validation come segue:

  • type: rappresenta il tipo di convalida, che può essere specificato utilizzando uno dei valori predefiniti nell’enumerazione ValidationType.
  • Operatore: rappresenta l’operatore da utilizzare nella convalida, che può essere specificato utilizzando uno dei valori predefiniti nell’enumerazione OperatorType.
  • formula1: rappresenta il valore o l’espressione associata alla prima parte della convalida dei dati.
  • formula2: rappresenta il valore o l’espressione associata alla seconda parte della convalida dei dati.

Quando le proprietà dell’oggetto Validation sono state configurate, gli sviluppatori possono utilizzare la struttura CellArea per memorizzare informazioni sull’intervallo di celle che verrà convalidato utilizzando la convalida creata.

Tipi di Convalida dei Dati

L’enumerazione ValidationType ha i seguenti membri:

Nome Membr* Descrizione
ANY_VALUE Denota un valore di qualsiasi tipo.
WHOLE_NUMBER Denota il tipo di convalida per numeri interi.
DECIMAL Denota il tipo di convalida per numeri decimali.
LIST Denota il tipo di convalida per elenco a discesa.
DATE Denota il tipo di convalida per date.
TIME Denota il tipo di convalida per orario.
TEXT_LENGTH Denota il tipo di convalida per la lunghezza del testo.
PERSONALIZZATO Indica il tipo di convalida personalizzato.
Convalida dei dati del numero intero

Con questo tipo di convalida, gli utenti possono inserire solo numeri interi entro un intervallo specificato nelle celle convalidatene. Gli esempi di codice che seguono mostrano come implementare il tipo di convalida del numero intero. L’esempio crea la stessa convalida dei dati utilizzando Aspose.Cells per Python via .NET che abbiamo creato utilizzando Microsoft Excel sopra.

from aspose.cells import CellArea, OperatorType, ValidationType, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Create a workbook object.
workbook = Workbook()
# Create a worksheet and get the first worksheet.
ExcelWorkSheet = workbook.worksheets[0]
# Accessing the Validations collection of the worksheet
validations = workbook.worksheets[0].validations
# Create Cell Area
ca = CellArea()
ca.start_row = 0
ca.end_row = 0
ca.start_column = 0
ca.end_column = 0
# Creating a Validation object
validation = validations[validations.add(ca)]
# Setting the validation type to whole number
validation.type = ValidationType.WHOLE_NUMBER
# Setting the operator for validation to Between
validation.operator = OperatorType.BETWEEN
# Setting the minimum value for the validation
validation.formula1 = "10"
# Setting the maximum value for the validation
validation.formula2 = "1000"
# Applying the validation to a range of cells from A1 to B2 using the
# CellArea structure
area = CellArea()
area.start_row = 0
area.end_row = 1
area.start_column = 0
area.end_column = 1
# Adding the cell area to Validation
validation.add_area(area)
# Save the workbook.
workbook.save("output.out.xls")
Convalida dei dati della lista

Questo tipo di convalida consente all’utente di inserire valori da un elenco a discesa. Fornisce un elenco: una serie di righe che contengono dati. Nell’esempio, viene aggiunta un secondo foglio di lavoro per contenere la fonte dell’elenco. Gli utenti possono selezionare solo valori dall’elenco. L’area di convalida è l’intervallo di celle A1:A5 nel primo foglio di lavoro.

È importante qui impostare la proprietà Validation.in_cell_drop_down su true.

from aspose.cells import CellArea, OperatorType, ValidationAlertType, ValidationType, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Create a workbook object.
workbook = Workbook()
# Get the first worksheet.
worksheet1 = workbook.worksheets[0]
# Add a new worksheet and access it.
i = workbook.worksheets.add()
worksheet2 = workbook.worksheets[i]
# Create a range in the second worksheet.
range = worksheet2.cells.create_range("E1", "E4")
# Name the range.
range.name = "MyRange"
# Fill different cells with data in the range.
worksheet2.cells.get("E1").value = "Blue"
worksheet2.cells.get("E2").value = "Red"
worksheet2.cells.get("E3").value = "Green"
worksheet2.cells.get("E4").value = "Yellow"
# Get the validations collection.
validations = worksheet1.validations
# Create Cell Area
ca = CellArea()
ca.start_row = 0
ca.end_row = 0
ca.start_column = 0
ca.end_column = 0
# Create a new validation to the validations list.
validation = validations[validations.add(ca)]
# Set the validation type.
validation.type = ValidationType.LIST
# Set the operator.
validation.operator = OperatorType.NONE
# Set the in cell drop down.
validation.in_cell_drop_down = True
# Set the formula1.
validation.formula1 = "=MyRange"
# Enable it to show error.
validation.show_error = True
# Set the alert type severity level.
validation.alert_style = ValidationAlertType.STOP
# Set the error title.
validation.error_title = "Error"
# Set the error message.
validation.error_message = "Please select a color from the list"
# Specify the validation area.
area = CellArea()
area.start_row = 0
area.end_row = 4
area.start_column = 0
area.end_column = 0
# Add the validation area.
validation.add_area(area)
# Save the Excel file.
workbook.save("output.out.xls")
Convalida dei dati della data

Con questo tipo di convalida, gli utenti inseriscono valori di data entro un intervallo specificato, o che soddisfano determinati criteri, nelle celle convalidate. Nell’esempio, all’utente è vietato inserire date comprese tra il 1970 e il 1999. Qui, l’area di convalida è la cella B1.

from aspose.cells import CellArea, OperatorType, ValidationAlertType, ValidationType, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Create a workbook.
workbook = Workbook()
# Obtain the cells of the first worksheet.
cells = workbook.worksheets[0].cells
# Put a string value into the A1 cell.
cells.get("A1").put_value("Please enter Date b/w 1/1/1970 and 12/31/1999")
# Set row height and column width for the cells.
cells.set_row_height(0, float(31))
cells.set_column_width(0, float(35))
# Get the validations collection.
validations = workbook.worksheets[0].validations
# Create Cell Area
ca = CellArea()
ca.start_row = 0
ca.end_row = 0
ca.start_column = 0
ca.end_column = 0
# Add a new validation.
validation = validations[validations.add(ca)]
# Set the data validation type.
validation.type = ValidationType.DATE
# Set the operator for the data validation
validation.operator = OperatorType.BETWEEN
# Set the value or expression associated with the data validation.
validation.formula1 = "1/1/1970"
# The value or expression associated with the second part of the data validation.
validation.formula2 = "12/31/1999"
# Enable the error.
validation.show_error = True
# Set the validation alert style.
validation.alert_style = ValidationAlertType.STOP
# Set the title of the data-validation error dialog box
validation.error_title = "Date Error"
# Set the data validation error message.
validation.error_message = "Enter a Valid Date"
# Set and enable the data validation input message.
validation.input_message = "Date Validation Type"
validation.ignore_blank = True
validation.show_input = True
# Set a collection of CellArea which contains the data validation settings.
cellArea = CellArea()
cellArea.start_row = 0
cellArea.end_row = 0
cellArea.start_column = 1
cellArea.end_column = 1
# Add the validation area.
validation.add_area(cellArea)
# Save the Excel file.
workbook.save("output.out.xls")
Convalida dei dati dell’ora

Con questo tipo di convalida, gli utenti possono inserire orari entro un intervallo specificato, o soddisfare alcuni criteri, nelle celle convalidate. Nell’esempio, all’utente è vietato inserire orari tra le 09:00 e le 11:30 del mattino. Qui, l’area di convalida è la cella B1.

from aspose.cells import CellArea, OperatorType, ValidationAlertType, ValidationType, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Create a workbook.
workbook = Workbook()
# Obtain the cells of the first worksheet.
cells = workbook.worksheets[0].cells
# Put a string value into A1 cell.
cells.get("A1").put_value("Please enter Time b/w 09:00 and 11:30 'o Clock")
# Set the row height and column width for the cells.
cells.set_row_height(0, float(31))
cells.set_column_width(0, float(35))
# Get the validations collection.
validations = workbook.worksheets[0].validations
# Create Cell Area
ca = CellArea()
ca.start_row = 0
ca.end_row = 0
ca.start_column = 0
ca.end_column = 0
# Add a new validation.
validation = validations[validations.add(ca)]
# Set the data validation type.
validation.type = ValidationType.TIME
# Set the operator for the data validation.
validation.operator = OperatorType.BETWEEN
# Set the value or expression associated with the data validation.
validation.formula1 = "09:00"
# The value or expression associated with the second part of the data validation.
validation.formula2 = "11:30"
# Enable the error.
validation.show_error = True
# Set the validation alert style.
validation.alert_style = ValidationAlertType.INFORMATION
# Set the title of the data-validation error dialog box.
validation.error_title = "Time Error"
# Set the data validation error message.
validation.error_message = "Enter a Valid Time"
# Set and enable the data validation input message.
validation.input_message = "Time Validation Type"
validation.ignore_blank = True
validation.show_input = True
# Set a collection of CellArea which contains the data validation settings.
cellArea = CellArea()
cellArea.start_row = 0
cellArea.end_row = 0
cellArea.start_column = 1
cellArea.end_column = 1
# Add the validation area.
validation.add_area(cellArea)
# Save the Excel file.
workbook.save("output.out.xls")
Convalida della lunghezza del testo

Con questo tipo di convalida, gli utenti possono inserire valori di testo di una lunghezza specificata nelle celle convalidate. Nell’esempio, all’utente è vietato inserire valori di stringa con più di 5 caratteri. L’area di convalida è la cella B1.

from aspose.cells import CellArea, OperatorType, ValidationAlertType, ValidationType, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Create a new workbook.
workbook = Workbook()
# Obtain the cells of the first worksheet.
cells = workbook.worksheets[0].cells
# Put a string value into A1 cell.
cells.get("A1").put_value("Please enter a string not more than 5 chars")
# Set row height and column width for the cell.
cells.set_row_height(0, float(31))
cells.set_column_width(0, float(35))
# Get the validations collection.
validations = workbook.worksheets[0].validations
# Create Cell Area
ca = CellArea()
ca.start_row = 0
ca.end_row = 0
ca.start_column = 0
ca.end_column = 0
# Add a new validation.
validation = validations[validations.add(ca)]
# Set the data validation type.
validation.type = ValidationType.TEXT_LENGTH
# Set the operator for the data validation.
validation.operator = OperatorType.LESS_OR_EQUAL
# Set the value or expression associated with the data validation.
validation.formula1 = "5"
# Enable the error.
validation.show_error = True
# Set the validation alert style.
validation.alert_style = ValidationAlertType.WARNING
# Set the title of the data-validation error dialog box.
validation.error_title = "Text Length Error"
# Set the data validation error message.
validation.error_message = " Enter a Valid String"
# Set and enable the data validation input message.
validation.input_message = "TextLength Validation Type"
validation.ignore_blank = True
validation.show_input = True
# Set a collection of CellArea which contains the data validation settings.
cellArea = CellArea()
cellArea.start_row = 0
cellArea.end_row = 0
cellArea.start_column = 1
cellArea.end_column = 1
# Add the validation area.
validation.add_area(cellArea)
# Save the Excel file.
workbook.save("output.out.xls")

Regole di convalida dei dati

Quando vengono implementate le convalide dei dati, allora la convalida può essere verificata assegnando valori diversi alle celle. Cell.get_validation_value() può essere utilizzato per recuperare il risultato della convalida. L’esempio seguente dimostra questa funzionalità con valori diversi. Il file di esempio può essere scaricato dal seguente link per il testing:

sampleDataValidationRules.xlsx

from aspose.cells import Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Instantiate the workbook from sample Excel file
workbook = Workbook("sample.xlsx")
# Access the first worksheet
worksheet = workbook.worksheets[0]
# Access Cell C1
# Cell C1 has the Decimal Validation applied on it.
# It can take only the values Between 10 and 20
cell = worksheet.cells.get("C1")
# Enter 3 inside this cell
# Since it is not between 10 and 20, it should fail the validation
cell.put_value(3)
# Check if number 3 satisfies the Data Validation rule applied on this cell
print("Is 3 a Valid Value for this Cell: " + str(cell.get_validation_value()))
# Enter 15 inside this cell
# Since it is between 10 and 20, it should succeed the validation
cell.put_value(15)
# Check if number 15 satisfies the Data Validation rule applied on this cell
print("Is 15 a Valid Value for this Cell: " + str(cell.get_validation_value()))
# Enter 30 inside this cell
# Since it is not between 10 and 20, it should fail the validation again
cell.put_value(30)
# Check if number 30 satisfies the Data Validation rule applied on this cell
print("Is 30 a Valid Value for this Cell: " + str(cell.get_validation_value()))

Verifica se la convalida nella cella è a discesa

Come abbiamo visto, ci sono molti tipi di convalida che possono essere implementati all’interno di una cella. Se si desidera verificare se la convalida è a discesa o no, può essere utilizzata la proprietà Validation.in_cell_drop_down per testare questo. Il codice di esempio seguente dimostra l’uso di questa proprietà. Un file di esempio per il testing può essere scaricato dal seguente link:

sampleValidation.xlsx

from aspose.cells import Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
book = Workbook("sampleValidation.xlsx")
sheet = book.worksheets.get("Sheet1")
cells = sheet.cells
a2 = cells.get("A2")
va2 = a2.get_validation()
if va2.in_cell_drop_down:
print("A2 is a dropdown")
else:
print("A2 is NOT a dropdown")
b2 = cells.get("B2")
vb2 = b2.get_validation()
if vb2.in_cell_drop_down:
print("B2 is a dropdown")
else:
print("B2 is NOT a dropdown")
c2 = cells.get("C2")
vc2 = c2.get_validation()
if vc2.in_cell_drop_down:
print("C2 is a dropdown")
else:
print("C2 is NOT a dropdown")

Aggiungi CellArea alla convalida esistente

Potrebbero esserci casi in cui si desidera aggiungere CellArea a Validation esistenti. Quando si aggiunge CellArea utilizzando Validation.add_area(cell_area), Aspose.Cells controlla tutte le aree esistenti per vedere se la nuova area esiste già. Se il file contiene un gran numero di convalide, si verifica un calo delle prestazioni. Per superare questo problema, l’API fornisce il metodo Validation.add_area(cell_area, check_intersection, check_edge). Il parametro checkIntersection indica se verificare l’intersezione di una data area con le aree di convalida esistenti. Impostarlo su false disabilita la verifica delle altre aree. Il parametro checkEdge indica se verificare le aree applicate. Se la nuova area diventa l’area in alto a sinistra, le impostazioni interne vengono ricostruite. Se si è sicuri che la nuova area non sia l’area in alto a sinistra, è possibile impostare questo parametro su false.

Il seguente frammento di codice dimostra l’uso del metodo Validation.add_area(cell_area, check_intersection, check_edge) per aggiungere nuove CellArea alle Validation esistenti.

from aspose.cells import CellArea, Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
workbook = Workbook("ValidationsSample.xlsx")
# Access first worksheet.
worksheet = workbook.worksheets[0]
# Accessing the Validations collection of the worksheet
validation = worksheet.validations[0]
# Create your cell area.
cellArea = CellArea.create_cell_area("D5", "E7")
# Adding the cell area to Validation
validation.add_area(cellArea, False, False)
# Save the output workbook.
workbook.save("ValidationsSample_out.xlsx")

I file excel sorgente e di output sono allegati a scopo informativo.

File di origine

File di output

Argomenti avanzati