前言:此隨筆僅供自己學習,如有不足請指出
在某些情況導出的時候,會有很複雜的表頭或者樣式,如果靠代碼去調整的話回很麻煩,需要寫很多代碼,這個時候可以預先設置好表格,這樣就方便靈活很多。
/// <summary> /// 使用模板導出Excel /// </summary> /// <param name="listEntity">數據集</param> /// <param name="path">路徑</param> /// <param name="index">從第幾行插入</param> /// <returns></returns> public static byte[] TemplateOutput(Array listEntity, string path, int index) { if ((listEntity?.Length ?? 0) == 0) { return new byte[] { }; } using (MemoryStream ms = new MemoryStream()) { Type entityType = listEntity.GetValue(0).GetType(); ; var entityProperties = entityType.GetProperties(); string extension = Path.GetExtension(path); FileStream fs = File.OpenRead(path); IWorkbook workbook = null; if (extension.Equals(".xls")) { workbook = new HSSFWorkbook(fs); } else { workbook = new XSSFWorkbook(fs); } fs.Close(); ISheet sheet = workbook.GetSheetAt(0); IRow rows = null; int i = 0; foreach (var dbitem in listEntity) { rows = sheet.CreateRow(i++ + index); for (int j = 0; j < entityProperties.Length; j++) { var prop = entityProperties[j]; var value = prop.GetValue(dbitem)?.ToString(); rows.CreateCell(j).SetCellValue(value ?? ""); } } workbook.Write(ms); return ms.ToArray(); } }