internal static IWorkbook ExecuteIWorkBookGet(ExcelVersionType versionType) { IWorkbook workbook = null; if (versionType == ExcelVersionType.Office2003) { workbook = new HSSFWorkbook(); } else { workbook = new XSSFWorkbook(); } return(workbook); }
internal static MemoryStream ExecuteIWorkbookStream(ExcelVersionType versionType, Action <IWorkbook> callback) { IWorkbook workbook = null; try { // 创建 Excel using (NPOIMemoryStream memoryStream = new NPOIMemoryStream()) { workbook = ExecuteIWorkBookGet(versionType); if (workbook == null) { throw new Exception(ExcelWorkbookNullException); } callback(workbook); workbook.Write(memoryStream); memoryStream.Flush(); memoryStream.Position = 0; return(memoryStream); } } catch { throw; } finally { if (workbook != null) { workbook.Close(); } } }
/// <summary> /// 根据实体数据列表输出 Excel 流 /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="dataList">实体数据列表</param> /// <param name="sheetName">Sheet 表单名称</param> /// <param name="propertyMatchList">属性匹配,Dictionary<string, object> 或 new {}</param> /// <param name="propertyList">属性列表,如果指定,则按指定属性列表生成 Excel</param> /// <param name="propertyContain">是否包含,true 属性包含,false 属性排除</param> /// <param name="cellCallback">单元格写入之后调用</param> /// <param name="sheetCallback">表单数据写入之后调用</param> /// <param name="isHeader">是否创建表头</param> /// <param name="columnValueFormat">列格式化,例:yyyy年MM月dd日</param> /// <param name="reflectionType">反射类型</param> /// <returns></returns> public static MemoryStream ToStream <T>(List <T> dataList, string sheetName, object propertyMatchList = null, string[] propertyList = null, bool propertyContain = true, Action <ICell, object> cellCallback = null, Action <ISheet, List <string> > sheetCallback = null, bool isHeader = true, object columnValueFormat = null, ExcelVersionType versionType = ExcelVersionType.Office2007, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new() { MemoryStream memoryStream = ExecuteIWorkbookStream(versionType, (IWorkbook workbook) => { SetWorkbookData(workbook, dataList, sheetName, propertyMatchList, propertyList, propertyContain, cellCallback, sheetCallback, isHeader, columnValueFormat, reflectionType); }); return(memoryStream); }