當所有列表項的總和時,字元總數超過 256
在這種情況下的方法將與前面的示例不同,因為 Excel 檔案支援對於總字元數小於 256 的專案列表的資料驗證,如果所有專案都直接繫結,如上例所示。但在許多情況下,列表項可能超過 256 個字元,在這種情況下,直接繫結將不起作用。
但是,如果從同一個 excel 檔案的不同列引用,則 excel 檔案支援超過 256 個字元的列表項。因此,一旦解決方法可以從資料庫或設定檔案中讀取所有值並將其從當前檢視隱藏到遠端列之一併且資料驗證可以通過公式讀取此隱藏列以建立列表項。下面的程式碼將通過設定檔案讀取資料值來顯示此方法。
// Read all list items from config file
string[] countryDV = ConfigurationManager.AppSettings["countryDV"].Split(',').Select(s => s.Trim().ToUpper()).ToArray();
// Get the column name where you want to hide the list items, assume distant column is "ZZ"
string countryDVDataCellColumn = ConfigurationManager.AppSettings["countryDVDataCellColumn"].Trim().ToString();
int DVRowLimit = (Int16.MaxValue);
// Creating and Assigning Settings for Data Validation
CreateDropDownUsingCellReference(workbook, countryDV, "CountryConstraint", countryDVDataCellColumn);
CellRangeAddressList countryDVAddList = new CellRangeAddressList(1, DVRowLimit, targetFirstCol, targetLastCol);
dvConstraint = (XSSFDataValidationConstraint)validationHelper.CreateFormulaListConstraint("=CountryConstraint");
dvConstraint.Validate();
dataValidation = (XSSFDataValidation)validationHelper.CreateValidation(dvConstraint, countryDVAddList);
dataValidation.ShowErrorBox = true;
dataValidation.SuppressDropDownArrow = true;
dataValidation.ErrorStyle = 0;
dataValidation.CreateErrorBox("InvalidValue", "Select Valid country.");
dataValidation.ShowErrorBox = true;
dataValidation.CreatePromptBox("country Data Validation", "Enter country.");
dataValidation.ShowPromptBox = true;
sheet.AddValidationData(dataValidation);
private void CreateDropDownUsingCellReference(XSSFWorkbook wb, string[] csvListOfValues, string listName, string headerName)
{
int columnIndex = CellReference.ConvertColStringToIndex(headerName);
try
{
XSSFName namedCell = (XSSFName)wb.CreateName();
namedCell.NameName = listName;
//Creating Cell and Assigning Values from CSVListOfValues;
for (int i = 0; i < csvListOfValues.Length; i++)
{
var namedRow = wb.GetSheetAt(0).CreateRow(i + 1);
namedRow.CreateCell(columnIndex).SetCellValue(csvListOfValues[i]);
}
//Assigning the Reference for sheet 0 With Cell Range, where list items iscopied
String reference = wb.GetSheetAt(0).SheetName + "!$" + headerName + "$2:$" + headerName + "$" + (csvListOfValues.Length + 1).ToString();
namedCell.RefersToFormula = reference;
//Hiding the Column now;
wb.GetSheetAt(0).SetColumnHidden(columnIndex, true);
}
catch (Exception Ex)
{ }
}