【推薦閱讀個人最新的Core版文章,是最全的介紹:C#_.NetCore_Web項目_EXCEL數據導出】html
須要引用NPOI的Nuget包:NPOI-v2.4.1app
B-1:EXCEL數據導入--C#獲取數據:post
/// <summary> /// EXCEL幫助類 /// </summary> /// <typeparam name="T">泛型類</typeparam> /// <typeparam name="TCollection">泛型類集合</typeparam> public class ExcelHelp<T, TCollection> where T : new() where TCollection : List<T>, new() { //http請求Request對象 public static HttpRequest baseRequest = HttpContext.Current.Request; //http請求Response對象 public static HttpResponse baseResponse = HttpContext.Current.Response; /// <summary> /// 將數據導出EXCEL /// </summary> /// <param name="columnNameAndShowNameDic">列名+顯示名</param> /// <param name="tColl">數據集(tColl裏的類屬性名必須和字典中的列名一致)</param> public static void ExportExcelData(Dictionary<string, string> columnNameAndShowNameDic, TCollection tColl) { IWorkbook workbook = new HSSFWorkbook(); ISheet worksheet = workbook.CreateSheet("sheet1"); List<string> columnNameList = columnNameAndShowNameDic.Keys.ToList(); List<string> showNameList = columnNameAndShowNameDic.Values.ToList(); //設置首列顯示 IRow row1 = worksheet.GetRow(0); ICell cell = null; for (var i = 0; i < columnNameList.Count; i++) { cell = row1.CreateCell(i); cell.SetCellValue(columnNameList[i]); } Dictionary<int, PropertyInfo> indexPropertyDic = GetIndexPropertyDic(columnNameList); for (int i = 0; i < tColl.Count; i++) { row1 = worksheet.GetRow(i + 1); for (int j = 0; j < indexPropertyDic.Count; j++) { cell = row1.CreateCell(i); cell.SetCellValue(indexPropertyDic[j].GetValue(tColl[i]).ToString()); } } MemoryStream ms = new MemoryStream(); workbook.Write(ms); byte[] buffer = ms.GetBuffer(); baseResponse.Clear(); baseResponse.Buffer = true; baseResponse.ContentEncoding = System.Text.Encoding.UTF8; //baseResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; baseResponse.ContentType = "application/vnd.ms-excel"; //設置導出文件名 baseResponse.AddHeader("content-disposition", "attachment; filename=" + "MaintainReport" + ".xlsx"); baseResponse.AddHeader("Content-Length", buffer.Length.ToString()); baseResponse.BinaryWrite(buffer); baseResponse.Flush(); baseResponse.End(); } /// <summary> /// 根據屬性名順序獲取對應的屬性對象 /// </summary> /// <param name="fieldNameList"></param> /// <returns></returns> private static Dictionary<int, PropertyInfo> GetIndexPropertyDic(List<string> fieldNameList) { Dictionary<int, PropertyInfo> indexPropertyDic = new Dictionary<int, PropertyInfo>(fieldNameList.Count); List<PropertyInfo> tPropertyInfoList = typeof(T).GetProperties().ToList(); PropertyInfo propertyInfo = null; for (int i = 0; i < fieldNameList.Count; i++) { propertyInfo = tPropertyInfoList.Find(m => m.Name.Equals(fieldNameList[i], StringComparison.OrdinalIgnoreCase)); indexPropertyDic.Add(i, propertyInfo); } return indexPropertyDic; } }