翻譯|使用教程|編輯:吉煒煒|2025-06-10 09:45:55.390|閱讀 107 次
概述:Excel 中的數據驗證可確保用戶在工作表中僅輸入有效數據。在設計表單、收集數據或構建財務模型時,數據驗證有助于維護結構并最大限度地減少用戶錯誤。在教程中,我們將向您展示如何使用 C# 以編程方式在 Excel 中應用數據驗證。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
Excel 中的數據驗證可確保用戶在工作表中僅輸入有效數據。在設計表單、收集數據或構建財務模型時,數據驗證有助于維護結構并最大限度地減少用戶錯誤。在本文中,我們將向您展示如何使用 C# 以編程方式在 Excel 中應用數據驗證。
數據驗證可確保用戶在 Excel 電子表格中輸入有效且符合預期的內容。我們將使用Aspose.Cells for .NET API 在 Excel 中添加不同類型的數據驗證。它提供了一種強大而靈活的方法來定義規則,例如下拉列表、數值范圍、日期限制和自定義公式,所有這些都無需 Microsoft Excel 即可實現。
在您的項目中通過包安裝 Aspose.Cells for .NET :
PM> Install-Package Aspose.Cells然后導入相關的命名空間:
using Aspose.Cells;
您可以通過在 Excel 中創建下拉列表驗證來將用戶輸入限制為一組預定義的選項。這可以確保值的一致性,這在表單或模板中尤其有用。
按照以下步驟使用 C# 在 Excel 中創建下拉列表:
以下是實現這些步驟的 C# 代碼示例:
// Create a new Excel workbook var workbook = new Workbook(); // Access the first worksheet in the workbook var sheet = workbook.Worksheets[0]; // Define the target cell area for validation (A1 in this case) var area = new CellArea { StartRow = 0, // Row index starts from 0 (Row 1) EndRow = 0, // Apply to a single row StartColumn = 0, // Column index starts from 0 (Column A) EndColumn = 0 // Apply to a single column }; // Access the validations collection of the worksheet var validations = sheet.Validations; // Add a new validation entry for the specified cell area int index = validations.Add(area); var validation = validations[index]; // Set the validation type to a dropdown list validation.Type = ValidationType.List; // Define the allowed list items (comma-separated values) validation.Formula1 = "Red,Green,Blue"; // Set the input message shown when the cell is selected validation.InputMessage = "Select a color from the list."; // Set the error message shown if invalid data is entered validation.ErrorMessage = "Only Red, Green, or Blue are allowed."; // Enable the display of the error message validation.ShowError = true; // Apply the defined area to the validation validation.AddArea(area); // Save the workbook to the specified file path workbook.Save("dropdown-validation.xlsx");
使用 C# 在 Excel 中創建下拉列表驗證
整數驗證可確保用戶在 Excel 中僅輸入有效的整數值,這對于數量字段、年齡輸入或不接受小數或文本的預算表非常有用。
假設您想限制一個單元格僅接受 1 到 100 之間的數字。如果沒有此規則,用戶可能會意外輸入無效輸入,例如 150 或 abc,從而導致電子表格出現計算錯誤或邏輯問題。
使用 Aspose.Cells for .NET,您可以在 C# 中以編程方式強制執行此驗證規則,而無需在 Excel 中手動配置它。
以下代碼片段顯示如何限制用戶僅輸入允許的值:
using Aspose.Cells; // Create a new Excel workbook var workbook = new Workbook(); // Access the first worksheet in the workbook var sheet = workbook.Worksheets[0]; // Define the target cell area — B2 (row 1, column 1) var area = new CellArea { StartRow = 1, EndRow = 1, StartColumn = 1, EndColumn = 1 }; // Access the worksheet’s validations collection var validations = sheet.Validations; // Add a new validation and get its index int index = validations.Add(area); // Retrieve the validation object using the index var validation = validations[index]; // Set validation type to WholeNumber (only integers allowed) validation.Type = ValidationType.WholeNumber; // Set the operator to Between validation.Operator = OperatorType.Between; // Define the valid range: 1 to 100 validation.Formula1 = "1"; validation.Formula2 = "100"; // Set the error message that appears when invalid data is entered validation.ErrorMessage = "Enter a number between 1 and 100."; // Enable showing the error alert when validation fails validation.ShowError = true; // (Optional if not using Add(area) earlier) Add the area to the validation explicitly validation.AddArea(area); // Save the workbook to a file workbook.Save("numbers-validation.xlsx");
使用 C# 在 Excel 中限制為整數
日期驗證可幫助您確保用戶僅輸入有效日期。它適用于規劃工具、考勤記錄、預訂表以及任何需要特定范圍內日期的場景。
例如,假設您正在構建一個項目調度模板,并且您想限制用戶只能輸入 2024 年內的日期。允許用戶輸入此范圍之外的日期(如 2023 年或 2025 年)可能會破壞公式或創建不一致的記錄。
Aspose.Cells for .NET 可以輕松地將日期驗證應用于特定單元格,因此用戶只能輸入符合您條件的日期。
以下代碼片段演示了如何確保用戶只能輸入 2024 年 1 月 1 日至 2024 年 12 月 31 日之間的日期。超出范圍的任何內容都會觸發錯誤,從而幫助您在整個電子表格中維護更清晰、更準確的數據。
using Aspose.Cells; // Create a new Excel workbook var workbook = new Workbook(); // Access the first worksheet in the workbook var sheet = workbook.Worksheets[0]; // Define the cell area to apply validation — C3 (row 2, column 2) var area = new CellArea { StartRow = 2, EndRow = 2, StartColumn = 2, EndColumn = 2 }; // Access the validations collection of the worksheet var validations = sheet.Validations; // Add a new validation and get its index int index = validations.Add(area); // Retrieve the validation object var validation = validations[index]; // Set the validation type to Date validation.Type = ValidationType.Date; // Set the operator to Between (start and end dates) validation.Operator = OperatorType.Between; // Specify the valid date range: Jan 1, 2024 to Dec 31, 2024 validation.Formula1 = "2024-01-01"; validation.Formula2 = "2024-12-31"; // Set the error message to display when the date is out of range validation.ErrorMessage = "Date must be within the year 2024."; // Enable showing the error alert validation.ShowError = true; // Re-apply the area to ensure validation is bound correctly validation.AddArea(area); // Save the workbook to the specified path workbook.Save("date-validation.xlsx");
有時,簡單的下拉菜單或固定數字范圍是不夠的,尤其是當您的規則依賴于其他單元格中的值時。借助基于公式的驗證,您可以使用 Excel 風格的公式定義自定義規則。這些規則可以引用其他單元格并動態評估輸入是否有效。例如,您可能希望確保單元格B1中的值始終大于A1中的值。這在價格比較、評分表或日期序列中很常見。
Aspose.Cells for .NET 完全支持此功能,并允許您像在 Excel 中一樣使用自定義公式定義驗證。
以下代碼示例顯示如何使用 C# 在 Excel 中應用基于公式的驗證。
using Aspose.Cells; // Create a new Excel workbook var workbook = new Workbook(); // Access the first worksheet in the workbook var sheet = workbook.Worksheets[0]; // Define the cell area for validation — B1 (row 0, column 1) var area = new CellArea { StartRow = 0, EndRow = 0, StartColumn = 1, EndColumn = 1 }; // Access the worksheets validations collection var validations = sheet.Validations; // Add a new validation to the collection and get its index int index = validations.Add(area); // Retrieve the validation object by index var validation = validations[index]; // Set the validation type to Custom (used for formula-based rules) validation.Type = ValidationType.Custom; // Set the custom formula: B1 must be greater than A1 validation.Formula1 = "=B1>A1"; // Define the error message shown when validation fails validation.ErrorMessage = "Value in B1 must be greater than A1."; // Enable display of the error alert on invalid input validation.ShowError = true; // Add the area explicitly to ensure it is covered by validation validation.AddArea(area); // Save the workbook to the specified file path workbook.Save("formula-validation.xlsx");
應用數據驗證只是解決方案的一部分。在用戶輸入錯誤數據時提供指導也同樣重要,而自定義警報和消息在此發揮著關鍵作用。
Aspose.Cells for .NET 允許您設置有用的輸入消息和錯誤警報,當用戶選擇單元格或輸入無效數據時會顯示這些消息。這些消息可以提升用戶體驗,減少混淆,并使您的 Excel 模板更加專業。
例如,當用戶點擊某個單元格時,您可以顯示如下工具提示
“僅允許 1 到 100 之間的值。”
如果他們輸入了錯誤的值,Excel 會顯示一個對話框,提示:
“無效輸入:請輸入一個介于 1 到 100 之間的數字。”
您還可以通過選擇是否完全阻止用戶 ( Stop)、允許他們繼續并顯示警告 ( Warning) 或僅顯示信息消息 ( Information) 來自定義 Excel 對無效輸入的響應方式。
按照以下步驟使用 C# 配置驗證警報:
這些警報使您的電子表格更加直觀和用戶友好,特別是當您創建模板供其他人頻繁使用或重復使用時。
var workbook = new Workbook(); var sheet = workbook.Worksheets[0]; // Set up validation area — apply to cell C1 var area = new CellArea { StartRow = 0, EndRow = 0, StartColumn = 2, // Column C = 2 EndColumn = 2 }; // Add validation int index = sheet.Validations.Add(area); var validation = sheet.Validations[index]; validation.Type = ValidationType.Custom; // This formula always evaluates to FALSE validation.Formula1 = "=FALSE"; // Set up input and error messages validation.InputTitle = "Input Restricted"; validation.InputMessage = "Try entering anything to see the validation."; validation.ErrorTitle = "Invalid Input"; validation.ErrorMessage = "You triggered this validation error successfully!"; validation.AlertStyle = ValidationAlertType.Stop; validation.ShowError = true; validation.ShowInput = true; // Apply validation to area validation.AddArea(area); // Save the validated workbook workbook.Save("D:\\Files\\validated_with_alerts.xlsx");
它們的警報增強了可用性并清楚地指導用戶輸入什么。
使用 C# 在 Excel 中配置輸入和錯誤消息
在本文中,我們展示了如何使用 Aspose.Cells for .NET 在 Excel 中使用 C# 實現數據驗證。從下拉菜單到自定義公式,您可以構建智能且防錯的電子表格,而無需依賴 Excel 本身。
————————————————————————————————————————
關于慧都科技:
慧都科技是一家行業數字化解決方案公司,長期專注于軟件、油氣與制造行業。公司基于深入的業務理解與管理洞察,以系統化的業務建模驅動技術落地,幫助企業實現智能化運營與長期競爭優勢。在軟件工程領域,我們提供開發控件、研發管理、代碼開發、部署運維等軟件開發全鏈路所需的產品,提供正版授權采購、技術選型、個性化維保等服務,幫助客戶實現技術合規、降本增效與風險可控。慧都科技Aspose在中國的官方授權代理商,提供Aspose系列產品免費試用,咨詢,正版銷售等于一體的專業化服務。Aspose是文檔處理領域的優秀產品,幫助企業高效構建文檔處理的應用程序。
下載|體驗更多Aspose產品,請咨詢,或撥打產品熱線:023-68661681
加入Aspose技術交流QQ群(1041253375),與更多小伙伴一起探討提升開發技能。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都網