/// <summary> /// 自定义列导出 /// </summary> /// <param name="sheetName">sheet名</param> /// <param name="title">标题</param> /// <param name="columns">自定义列 字段名</param> /// <param name="tList">对象集合</param> /// <param name="path">保存路径</param> public static void ExportCom<T>(string sheetName, string title, string columns, List<T> tList, string path) where T:new () { IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(sheetName); ICellStyle style = workbook.CreateCellStyle(); //设置单元格的样式:水平对齐居中 style.Alignment = HorizontalAlignment.CENTER; //新建一个字体样式对象 IFont font = workbook.CreateFont(); //设置字体加粗样式 font.Boldweight = short.MaxValue; font.FontHeight = 300; //使用SetFont方法将字体样式添加到单元格样式中 style.SetFont(font); var colArr = columns.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); IRow rowtitle = sheet.CreateRow(0); rowtitle.Height = 30 * 20; ICell cellTitle = rowtitle.CreateCell(0); IRow row1 = sheet.CreateRow(1); row1.Height = 20 * 20; int emp = 0; //列 中文 for (int i = 0; i < colArr.Count(); i++) { var colName = GetNameByColumn(colArr[i]); if (!string.IsNullOrEmpty(colName)) { ICell cellYmw = row1.CreateCell(i - emp); cellYmw.SetCellValue(colName); } else { emp++; } } //标题栏 cellTitle.SetCellValue(title + DateTime.Now.ToString("yyyyMMddHHmmss")); cellTitle.CellStyle = style; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, colArr.Length - emp)); //值 for (int i = 0; i < tList.Count; i++) { IRow row = sheet.CreateRow(i + 2); int ept = 0; for (int j = 0; j < colArr.Count(); j++) { var colName = GetNameByColumnCom<T>(colArr[j]); if (!string.IsNullOrEmpty(colName)) { var obj = ObjValueCom<T>(colArr[j], tList[i]); ICell cellName = row.CreateCell(j - ept); cellName.SetCellValue(obj); } else { ept++; } } } FileStream file = new FileStream(path, FileMode.OpenOrCreate); workbook.Write(file); file.Flush(); file.Close(); } /// <summary> /// 根据列名获取列值 /// </summary> /// <param name="colName"></param> /// <param name="item"></param> /// <returns></returns> public static string ObjValueCom<T>(string colName, T item) where T : new() { object obj = ""; Type type = typeof(T); var proInfo = type.GetProperty(colName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (proInfo != null) { obj = proInfo.GetValue(item, null); } return obj.ToString(); } /// <summary> /// 根据列名 得到对应列注释 对应类必须有注释 /// </summary> /// <param name="colName"></param> /// <returns></returns> public static string GetNameByColumnCom<T>(string colName) { string proName = ""; var protityes = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); foreach (var prperoty in protityes) { object[] objs = prperoty.GetCustomAttributes(typeof(DescriptionAttribute), true); if (prperoty.Name == colName) { proName = ((DescriptionAttribute)objs[0]).Description; } } return proName; }