使用NPOI的库进行Excel导出操作
公共帮助类:
1 using NPOI.HSSF.UserModel; 2 using NPOI.SS.UserModel; 3 using System; 4 using System.Collections.Generic; 5 using System.Data; 6 using System.IO; 7 using System.Linq; 8 using System.Reflection; 9 using System.Text; 10 using System.Web; 11 12 namespace Common.Helper 13 { 14 /// <summary> 15 /// 创建人员:杨汨 16 /// 创建时间:2017-05-10 17 /// 创建说明:Excel 帮助类 18 /// </summary> 19 public static class ExcelHelper 20 { 21 //列宽的预留宽度 22 private const int WID = 2; 23 24 #region DataTable 操作 25 /// <summary> 26 /// 将DataTable 转换为 HSSFWorkbook Excel 27 /// </summary> 28 /// <param name="dt">数据源 DataTable</param> 29 /// <returns>HSSFWorkbook</returns> 30 public static HSSFWorkbook WriteTableToBook(DataTable dt, string sheetName = "Sheet1") 31 { 32 HSSFWorkbook book = new HSSFWorkbook(); 33 if (dt == null || dt.Rows.Count <= 0) 34 { 35 return book; 36 } 37 try 38 { 39 ISheet sheet = book.CreateSheet(sheetName); 40 41 DataColumnCollection cols = dt.Columns; 42 int rIndex = 0; 43 //设置表头 44 ICellStyle style = GetHeaderStyle(book); 45 IRow rowHeader = sheet.CreateRow(rIndex); 46 for (int j = 0; j < cols.Count; j++) 47 { 48 ICell cell = rowHeader.CreateCell(j); 49 cell.CellStyle = style; 50 cell.SetCellValue(cols[j].ColumnName); 51 } 52 //设置内容 53 rIndex++; 54 string val = null; 55 for (int i = rIndex; i < (dt.Rows.Count + rIndex); i++) 56 { 57 IRow row = sheet.CreateRow(i); 58 for (int j = 0; j < cols.Count; j++) 59 { 60 ICell cell = row.CreateCell(j); 61 cell.SetCellType(GetCellType(cols[j].DataType)); 62 val = dt.Rows[i - rIndex][cols[j].ColumnName].ToString(); 63 cell.SetCellValue(val); 64 sheet.SetColumnWidth(j, (Encoding.UTF8.GetBytes(val).Length + WID) * 256); 65 } 66 } 67 } 68 catch (Exception ex) 69 { 70 throw; 71 } 72 return book; 73 } 74 75 /// <summary> 76 /// 将DataTable 转换为 MemoryStream 的 Excel 77 /// </summary> 78 /// <param name="dt">数据源 DataTable</param> 79 /// <returns>MemoryStream</returns> 80 public static MemoryStream WriteTableToStream(DataTable dt, string sheetName = "Sheet1") 81 { 82 MemoryStream ms = new MemoryStream(); 83 HSSFWorkbook book = WriteTableToBook(dt,sheetName); 84 book.Write(ms); 85 return ms; 86 } 87 88 /// <summary> 89 /// 自定义设置表格表头名称 90 /// </summary> 91 /// <param name="dt"></param> 92 /// <param name="dicNames"></param> 93 public static void SetColName(DataTable dt , Dictionary<string,string> dicNames) 94 { 95 foreach (var key in dicNames.Keys) 96 { 97 dt.Columns[key].ColumnName = dicNames[key]; 98 } 99 } 100 101 102 103 #endregion 104 105 #region List 集合操作 106 /// <summary> 107 /// 将集合写入 HSSFWorkbook 的Excel 108 /// </summary> 109 /// <typeparam name="T">数据类型</typeparam> 110 /// <param name="list">数据集合</param> 111 /// <param name="sheetName">sheet名称</param> 112 /// <returns>HSSFWorkbook</returns> 113 public static HSSFWorkbook WriteListToBook<T>(List<T> list, string sheetName = "Sheet1") 114 { 115 HSSFWorkbook book = new HSSFWorkbook(); 116 if (list == null || list.Count <= 0) 117 { 118 return book; 119 } 120 Type t = typeof(T); 121 PropertyInfo[] props = t.GetProperties(); 122 123 ISheet sheet = book.CreateSheet(sheetName); 124 125 int rIndex = 0; 126 127 //创建头 128 ICellStyle style = GetHeaderStyle(book); 129 IRow rowHeader = sheet.CreateRow(rIndex); 130 for (int i = 0; i < props.Length; i++) 131 { 132 ICell cell = rowHeader.CreateCell(i); 133 cell.CellStyle = style; 134 cell.SetCellValue(props[i].Name); 135 } 136 137 rIndex++; 138 string val = null; 139 foreach (T item in list) 140 { 141 IRow row = sheet.CreateRow(rIndex++); 142 for (int i = 0; i < props.Length; i++) 143 { 144 ICell cell = row.CreateCell(i); 145 cell.SetCellType(GetCellType(props[i].PropertyType)); 146 val =props[i].GetValue(item,null).ToString(); 147 cell.SetCellValue(val); 148 sheet.SetColumnWidth(i, (Encoding.UTF8.GetBytes(val).Length + WID) * 256); 149 } 150 } 151 return book; 152 } 153 154 /// <summary> 155 /// 将集合写入MemoryStream 的Excel 156 /// </summary> 157 /// <typeparam name="T">数据类型</typeparam> 158 /// <param name="list">数据集合</param> 159 /// <param name="sheetName">sheet名称</param> 160 /// <returns>MemoryStream</returns> 161 public static MemoryStream WriteListToStream<T>(List<T> list, string sheetName = "Sheet1") 162 { 163 HSSFWorkbook book = WriteListToBook(list, sheetName); 164 MemoryStream ms = new MemoryStream(); 165 book.Write(ms); 166 return ms; 167 } 168 #endregion 169 170 #region 内部方法 171 172 /// <summary> 173 /// 获取单元格存储类型 174 /// </summary> 175 /// <param name="t">C# 类型</param> 176 /// <returns>CellType</returns> 177 private static CellType GetCellType(Type t) 178 { 179 switch (t.ToString().ToLower()) 180 { 181 case "string": 182 return CellType.String; 183 case "int16": 184 case "int32": 185 case "int64": 186 return CellType.Numeric; 187 case "boolean": 188 return CellType.Boolean; 189 default: 190 return CellType.String; 191 } 192 } 193 194 /// <summary> 195 /// 获取表头样式 196 /// </summary> 197 /// <param name="book"></param> 198 /// <returns></returns> 199 private static ICellStyle GetHeaderStyle(HSSFWorkbook book) 200 { 201 //设置表头 202 IFont font = book.CreateFont(); 203 //font.Boldweight= (short)FontBoldWeight.Bold; 204 font.IsBold = true; 205 font.FontHeightInPoints = 12; 206 ICellStyle style = book.CreateCellStyle(); 207 style.SetFont(font); 208 return style; 209 } 210 #endregion 211 212 } 213 }
在MVC的控制器中进行导出
1 public ActionResult ExcelOut() 2 { 3 //从业务层获取需要导出的DataTable类型的数据 4 DataTable dt = BIZ_EDU_FLOW_BLL.Instance.GetChargedList(); 5 if (dt != null) 6 { 7 //dt 的自定义二次操作 8 ReconstructionTable(dt); 9 } 10 else 11 { 12 dt = new DataTable(); 13 } 14 MemoryStream ms = Common.Helper.ExcelHelper.WriteTableToStream(dt); 15 string fileName = "已收费学员信息-" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + ".xls"; 16 //ms.Seek(0, SeekOrigin.Begin); 17 //File(ms, "application/ms-excel", fileName); //这种方式下载的时候必须使用 ms.Seek(); 18 return File(ms.ToArray(), "application/ms-excel", Url.Encode(fileName)); 19 }
1 /// <summary> 2 /// 自定义重构DataTable 3 /// </summary> 4 /// <param name="dt"></param> 5 private static void ReconstructionTable(DataTable dt) 6 { 7 dt.Columns.Add("JYJBStr", typeof(string)); 8 dt.Columns.Add("JYLXStr", typeof(string)); 9 dt.Columns.Add("JYZTStr", typeof(string)); 10 dt.Columns.Add("ZFFSStr", typeof(string)); 11 foreach (DataRow dr in dt.Rows) 12 { 13 dr["JYJBStr"] = dr["JYJB"].ToString() == "1" ? "普通" : "重点"; 14 dr["JYLXStr"] = dr["JYLX"].ToString() == "1" ? "满分" : "审验"; 15 dr["JYZTStr"] = BLL.ParaDict.JYZT[dr["JYZT"].ToString()]; 16 dr["ZFFSStr"] = dr["ZFFS"].ToString() == "1" ? "现金" : "Pos刷卡"; 17 } 18 dt.Columns.Remove("JYJB"); 19 dt.Columns.Remove("JYLX"); 20 dt.Columns.Remove("JYZT"); 21 dt.Columns.Remove("ZFFS"); 22 23 //dt 的自定义二次操作 24 Dictionary<string, string> dic = new Dictionary<string, string>(); 25 dic.Add("ID", "序号"); 26 dic.Add("XM", "姓名"); 27 dic.Add("SFZH", "身份证号"); 28 dic.Add("JYJBStr", "教育级别"); 29 dic.Add("JYLXStr", "教育类型"); 30 dic.Add("LXDH", "联系电话"); 31 dic.Add("JYZTStr", "教育状态"); 32 dic.Add("JE", "金额"); 33 dic.Add("SFR", "收费人"); 34 dic.Add("SFSJ", "收费时间"); 35 dic.Add("ZFFSStr", "支付方式"); 36 Common.Helper.ExcelHelper.SetColName(dt, dic); 37 }