Excel 下拉選單

public void GenerateWithValidation<T>(string TemplatePath, string ReportPath, List<T> entities, int Offset, int PageSize) { using (FileStream fileStream = new FileStream(TemplatePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { IWorkbook workbook = WorkbookFactory.Create(fileStream); ISheet sheet = workbook.GetSheetAt(0); List<ICell> TemplateCells = new List<ICell>(); for (int i = 0; i < sheet.GetRow(Offset).Cells.Count; i++) { TemplateCells.Add(sheet.GetRow(Offset).GetCell(i)); } PropertyInfo[] properties = typeof(T).GetProperties(); foreach (var entity in entities) { sheet.CreateRow(Offset); int CellInRow = 0; foreach (var property in properties) { ICell cell = sheet.GetRow(Offset).CreateCell(CellInRow); cell.CellStyle = TemplateCells[CellInRow].CellStyle; cell.SetCellType(TemplateCells[CellInRow].CellType); if (TemplateCells[CellInRow].CellType.Equals(CellType.Numeric)) { cell.SetCellValue(Convert.ToDouble(property.GetValue(entity, null))); } else { cell.SetCellValue(Convert.ToString(property.GetValue(entity, null))); } CellInRow++; } Offset++; }         //主要是這段 for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i];

            //判斷是否為Enum 是的話則做成下拉選單 if (property.PropertyType.IsEnum) { CellRangeAddressList addressList = new CellRangeAddressList(0, sheet.LastRowNum, i, i); var helper = sheet.GetDataValidationHelper(); var constraint = helper.CreateExplicitListConstraint(Enum.GetNames(property.PropertyType)); var validation = helper.CreateValidation(constraint, addressList); sheet.AddValidationData(validation); } } using (FileStream fileOut = new FileStream(ReportPath, FileMode.Create)) { workbook.Write(fileOut); } }

}


參考 :

https://dotblogs.com.tw/stanley14/2018/02/06/NPOI_Excel_DropDownList

留言

這個網誌中的熱門文章

無法載入檔案或組件 'System.IO.Compression' 或其相依性的其中之一。

MongoDB 入門

javascript 更改屬性及創建標籤