/// <summary> /// 读取Excel并转换为给定类型数组 /// </summary> /// <param name="path">读取路径</param> /// <param name="sheetName">工作表名称</param> /// <param name="rowIndex">行索引</param> /// <returns>给定类型数组</returns> /// <remarks>默认读取第二行</remarks> public static T[] ReadFile <T>(string path, string sheetName, int rowIndex = 1) { #region # 验证 if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(nameof(path), "文件路径不可为空!"); } if (string.IsNullOrWhiteSpace(sheetName)) { throw new ArgumentNullException(nameof(sheetName), "工作表名称不可为空!"); } if (rowIndex < 0) { rowIndex = 0; } #endregion //01.创建文件流 using (FileStream stream = File.OpenRead(path)) { //02.创建工作薄 string extensionName = Path.GetExtension(path); IWorkbook workbook = ExcelConductor.CreateWorkbook(extensionName, stream); //03.读取给定工作表 ISheet sheet = workbook.GetSheet(sheetName); //04.返回集合 return(SheetToArray <T>(sheet, rowIndex)); } }
//Private #region # 创建工作簿 —— static IWorkbook CreateWorkbook<T>(string extensionName... /// <summary> /// 创建工作簿 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="extensionName">扩展名</param> /// <param name="array">对象数组</param> /// <param name="titles">标题集</param> /// <returns>工作簿</returns> private static IWorkbook CreateWorkbook <T>(string extensionName, T[] array, string[] titles = null) { //01.创建工作簿 IWorkbook workbook = ExcelConductor.CreateWorkbook(extensionName); //02.创建工作表 ISheet sheet = workbook.CreateSheet(typeof(T).Name); #region //03.创建标题行 IRow rowTitle = sheet.CreateRow(0); string[] defaultTitles = typeof(T).GetProperties().Select(x => x.Name).ToArray(); if (titles == null) { CreateTitleRow(defaultTitles, rowTitle); } else { #region # 验证 if (titles.Length != defaultTitles.Length) { throw new ArgumentOutOfRangeException(nameof(titles), "标题列数与数据列数不一致!"); } #endregion CreateTitleRow(titles, rowTitle); } #endregion //04.创建数据行 CreateDataRows(array, sheet); return(workbook); }