翻譯|使用教程|編輯:吉煒煒|2025-06-10 09:45:55.390|閱讀 107 次
概述:Excel 中的數(shù)據(jù)驗(yàn)證可確保用戶在工作表中僅輸入有效數(shù)據(jù)。在設(shè)計(jì)表單、收集數(shù)據(jù)或構(gòu)建財(cái)務(wù)模型時(shí),數(shù)據(jù)驗(yàn)證有助于維護(hù)結(jié)構(gòu)并最大限度地減少用戶錯(cuò)誤。在教程中,我們將向您展示如何使用 C# 以編程方式在 Excel 中應(yīng)用數(shù)據(jù)驗(yàn)證。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
Excel 中的數(shù)據(jù)驗(yàn)證可確保用戶在工作表中僅輸入有效數(shù)據(jù)。在設(shè)計(jì)表單、收集數(shù)據(jù)或構(gòu)建財(cái)務(wù)模型時(shí),數(shù)據(jù)驗(yàn)證有助于維護(hù)結(jié)構(gòu)并最大限度地減少用戶錯(cuò)誤。在本文中,我們將向您展示如何使用 C# 以編程方式在 Excel 中應(yīng)用數(shù)據(jù)驗(yàn)證。
數(shù)據(jù)驗(yàn)證可確保用戶在 Excel 電子表格中輸入有效且符合預(yù)期的內(nèi)容。我們將使用Aspose.Cells for .NET API 在 Excel 中添加不同類型的數(shù)據(jù)驗(yàn)證。它提供了一種強(qiáng)大而靈活的方法來(lái)定義規(guī)則,例如下拉列表、數(shù)值范圍、日期限制和自定義公式,所有這些都無(wú)需 Microsoft Excel 即可實(shí)現(xiàn)。
在您的項(xiàng)目中通過(guò)包安裝 Aspose.Cells for .NET :
PM> Install-Package Aspose.Cells然后導(dǎo)入相關(guān)的命名空間:
using Aspose.Cells;
您可以通過(guò)在 Excel 中創(chuàng)建下拉列表驗(yàn)證來(lái)將用戶輸入限制為一組預(yù)定義的選項(xiàng)。這可以確保值的一致性,這在表單或模板中尤其有用。
按照以下步驟使用 C# 在 Excel 中創(chuàng)建下拉列表:
以下是實(shí)現(xiàn)這些步驟的 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 中創(chuàng)建下拉列表驗(yàn)證
整數(shù)驗(yàn)證可確保用戶在 Excel 中僅輸入有效的整數(shù)值,這對(duì)于數(shù)量字段、年齡輸入或不接受小數(shù)或文本的預(yù)算表非常有用。
假設(shè)您想限制一個(gè)單元格僅接受 1 到 100 之間的數(shù)字。如果沒有此規(guī)則,用戶可能會(huì)意外輸入無(wú)效輸入,例如 150 或 abc,從而導(dǎo)致電子表格出現(xiàn)計(jì)算錯(cuò)誤或邏輯問(wèn)題。
使用 Aspose.Cells for .NET,您可以在 C# 中以編程方式強(qiáng)制執(zhí)行此驗(yàn)證規(guī)則,而無(wú)需在 Excel 中手動(dòng)配置它。
以下代碼片段顯示如何限制用戶僅輸入允許的值:
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 中限制為整數(shù)
日期驗(yàn)證可幫助您確保用戶僅輸入有效日期。它適用于規(guī)劃工具、考勤記錄、預(yù)訂表以及任何需要特定范圍內(nèi)日期的場(chǎng)景。
例如,假設(shè)您正在構(gòu)建一個(gè)項(xiàng)目調(diào)度模板,并且您想限制用戶只能輸入 2024 年內(nèi)的日期。允許用戶輸入此范圍之外的日期(如 2023 年或 2025 年)可能會(huì)破壞公式或創(chuàng)建不一致的記錄。
Aspose.Cells for .NET 可以輕松地將日期驗(yàn)證應(yīng)用于特定單元格,因此用戶只能輸入符合您條件的日期。
以下代碼片段演示了如何確保用戶只能輸入 2024 年 1 月 1 日至 2024 年 12 月 31 日之間的日期。超出范圍的任何內(nèi)容都會(huì)觸發(fā)錯(cuò)誤,從而幫助您在整個(gè)電子表格中維護(hù)更清晰、更準(zhǔn)確的數(shù)據(jù)。
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");
有時(shí),簡(jiǎn)單的下拉菜單或固定數(shù)字范圍是不夠的,尤其是當(dāng)您的規(guī)則依賴于其他單元格中的值時(shí)。借助基于公式的驗(yàn)證,您可以使用 Excel 風(fēng)格的公式定義自定義規(guī)則。這些規(guī)則可以引用其他單元格并動(dòng)態(tài)評(píng)估輸入是否有效。例如,您可能希望確保單元格B1中的值始終大于A1中的值。這在價(jià)格比較、評(píng)分表或日期序列中很常見。
Aspose.Cells for .NET 完全支持此功能,并允許您像在 Excel 中一樣使用自定義公式定義驗(yàn)證。
以下代碼示例顯示如何使用 C# 在 Excel 中應(yīng)用基于公式的驗(yàn)證。
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");
應(yīng)用數(shù)據(jù)驗(yàn)證只是解決方案的一部分。在用戶輸入錯(cuò)誤數(shù)據(jù)時(shí)提供指導(dǎo)也同樣重要,而自定義警報(bào)和消息在此發(fā)揮著關(guān)鍵作用。
Aspose.Cells for .NET 允許您設(shè)置有用的輸入消息和錯(cuò)誤警報(bào),當(dāng)用戶選擇單元格或輸入無(wú)效數(shù)據(jù)時(shí)會(huì)顯示這些消息。這些消息可以提升用戶體驗(yàn),減少混淆,并使您的 Excel 模板更加專業(yè)。
例如,當(dāng)用戶點(diǎn)擊某個(gè)單元格時(shí),您可以顯示如下工具提示
“僅允許 1 到 100 之間的值。”
如果他們輸入了錯(cuò)誤的值,Excel 會(huì)顯示一個(gè)對(duì)話框,提示:
“無(wú)效輸入:請(qǐng)輸入一個(gè)介于 1 到 100 之間的數(shù)字?!?/em>
您還可以通過(guò)選擇是否完全阻止用戶 ( Stop)、允許他們繼續(xù)并顯示警告 ( Warning) 或僅顯示信息消息 ( Information) 來(lái)自定義 Excel 對(duì)無(wú)效輸入的響應(yīng)方式。
按照以下步驟使用 C# 配置驗(yàn)證警報(bào):
這些警報(bào)使您的電子表格更加直觀和用戶友好,特別是當(dāng)您創(chuàng)建模板供其他人頻繁使用或重復(fù)使用時(shí)。
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");
它們的警報(bào)增強(qiáng)了可用性并清楚地指導(dǎo)用戶輸入什么。
使用 C# 在 Excel 中配置輸入和錯(cuò)誤消息
在本文中,我們展示了如何使用 Aspose.Cells for .NET 在 Excel 中使用 C# 實(shí)現(xiàn)數(shù)據(jù)驗(yàn)證。從下拉菜單到自定義公式,您可以構(gòu)建智能且防錯(cuò)的電子表格,而無(wú)需依賴 Excel 本身。
————————————————————————————————————————
關(guān)于慧都科技:
慧都科技是一家行業(yè)數(shù)字化解決方案公司,長(zhǎng)期專注于軟件、油氣與制造行業(yè)。公司基于深入的業(yè)務(wù)理解與管理洞察,以系統(tǒng)化的業(yè)務(wù)建模驅(qū)動(dòng)技術(shù)落地,幫助企業(yè)實(shí)現(xiàn)智能化運(yùn)營(yíng)與長(zhǎng)期競(jìng)爭(zhēng)優(yōu)勢(shì)。在軟件工程領(lǐng)域,我們提供開發(fā)控件、研發(fā)管理、代碼開發(fā)、部署運(yùn)維等軟件開發(fā)全鏈路所需的產(chǎn)品,提供正版授權(quán)采購(gòu)、技術(shù)選型、個(gè)性化維保等服務(wù),幫助客戶實(shí)現(xiàn)技術(shù)合規(guī)、降本增效與風(fēng)險(xiǎn)可控?;鄱伎萍?span style="color:#FF9900;">Aspose在中國(guó)的官方授權(quán)代理商,提供Aspose系列產(chǎn)品免費(fèi)試用,咨詢,正版銷售等于一體的專業(yè)化服務(wù)。Aspose是文檔處理領(lǐng)域的優(yōu)秀產(chǎn)品,幫助企業(yè)高效構(gòu)建文檔處理的應(yīng)用程序。
下載|體驗(yàn)更多Aspose產(chǎn)品,請(qǐng)咨詢,或撥打產(chǎn)品熱線:023-68661681
加入Aspose技術(shù)交流QQ群(1041253375),與更多小伙伴一起探討提升開發(fā)技能。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:慧都網(wǎng)