c# 導入導出excel方法封裝


public class ExportAttribute : Attribute { public ExportAttribute(bool needExport = true) { _NeedExport = needExport; } private bool _NeedExport { set; get; } /// /// 是否需要導出的字段 /// public bool NeedExport { get { return _NeedExport; } set { _NeedExport = value; } } } /// /// 導出excel幫助類 /// /// public class ExcelHelper { /// /// 屬性描述與類集合緩存 /// private static Dictionary<Type, List> _propertyNameDic; /// /// 屬性與類集合緩存 /// private static Dictionary<Type, PropertyInfo[]> _propertyDic; /// /// 屬性與描述對應關系集合緩存 /// public static Dictionary<Type, List> _displayMappProperty; private string fileName = null; //文件名 private HSSFWorkbook workbook = null; private XSSFWorkbook xworkbook = null; private FileStream fs = null; private bool disposed; public ExcelHelper() { } /// /// 有參構造函數 導入EXCEL 時使用 /// /// public ExcelHelper(string fileName) { this.fileName = fileName; disposed = false; } /// /// 將excel中的數據導入到實體集合中 /// 使用說明:1.傳入的實體屬性中displayName描述對應excel中的列名 /// ///文件 ///sheet名稱 ///起始第一行(excel列名開始行) ///返回的指定的實體集合 public List ExcelToModel(HttpPostedFileBase file, string sheetName = null, int firstRow = 0) where T : new() { var models = new List(); DataTable data = new DataTable(); try { using (Stream fs = file.InputStream) { fileName = file.FileName; var fileNameArray = fileName.Split('.'); if (fileNameArray.Length == 2) { ISheet sheet = null; if (fileNameArray[1].ToLower().Trim() == "xls") { workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } else { xworkbook = new XSSFWorkbook(fs); if (sheetName != null) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } models = GetModel(sheet, models, firstRow); } else { return null; } } return models; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return null; } } /// /// 保存文件到本地,並且數據轉化為實體 /// ///文件 ///文件保存路徑 ///sheet名稱 ///起始第一行(excel列名開始行) /// public List ExcelToModelAndSave(HttpPostedFileBase file, string savePath, string sheetName = null, int firstRow = 0) where T : new() { var models = new List(); DataTable data = new DataTable(); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } try { using (Stream fs = file.InputStream) { fileName = file.FileName; var fileNameArray = fileName.Split('.'); if (fileNameArray.Length == 2) { ISheet sheet = null; if (fileNameArray[1].ToLower().Trim() == "xls") { savePath = $"{savePath}\\{DateTime.Now.ToString("dd-HH-mm-ss")}.xls"; workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } else { savePath = $"{savePath}\\{DateTime.Now.ToString("dd-HH-mm-ss")}.xlsx"; xworkbook = new XSSFWorkbook(fs); if (sheetName != null) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } models = GetModel(sheet, models, firstRow); } else { return null; } } file.SaveAs(savePath); return models; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return null; } } /// /// 導出Excel /// 使用說明:1.實體中屬性的displayName為導出excel中對應的列名,如果沒有則按照屬性名稱 /// 2.實體的屬性最好都是字符串或者數字類型的,在展示過程中,不會進行數據轉化 /// ///需要導出的實體模型(實體的屬性最好都是字符串或者數字類型的,在展示過程中,不會進行數據轉化) ///請求上下文 ///導出的文件名(默認時間) ///文件頭備注 ///文件底部備注(eg:統計數據的添加) public void Export(List models, HttpResponseBase Response, string fileName, string remark, string addUp) { //首先獲取excel中的列名 Type type = typeof(T); List propertyNames = GetDisplayNames(type); //Create a new workbook var workbook = new XSSFWorkbook(); //create a new sheet var sheet = workbook.CreateSheet("User Accounts"); // Add header labels var rowIndex = 0; var rowLength = 0; //存儲文件頭備注 if (!string.IsNullOrEmpty(remark)) { var rowRemark = sheet.CreateRow(rowIndex); rowRemark.CreateCell(rowIndex).SetCellValue(remark); //合並單元格 sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, propertyNames.Count - 1)); rowIndex++; } var row = sheet.CreateRow(rowIndex); //存儲列名 foreach (var propertyName in propertyNames) { row.CreateCell(rowLength).SetCellValue(propertyName); rowLength++; } //存儲值 var propertieValues = _propertyDic[type]; foreach (var model in models) { rowIndex++; row = sheet.CreateRow(rowIndex); for (var m = 0; m < rowLength; m++) { var value = propertieValues[m].GetValue(model, null); row.CreateCell(m).SetCellValue(value?.ToString()); } } //存儲文件尾備注(EG:統計數據) if (!string.IsNullOrEmpty(addUp)) { row = sheet.CreateRow(rowIndex + 1); row.CreateCell(0).SetCellValue(addUp); //合並單元格 sheet.AddMergedRegion(new CellRangeAddress(rowIndex + 1, rowIndex + 2, 0, propertyNames.Count - 1)); } fileName = $"{fileName}{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}"; ExportExcel(workbook, Response, fileName); } /// /// 導出文件到瀏覽器 /// /// /// ///文件名稱 private void ExportExcel(XSSFWorkbook workbook, HttpResponseBase Response, string fileName) { using (var exportData = new MemoryStream()) { workbook.Write(exportData); Response.Buffer = true; Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); //response.ContentType = "application/ms-excel"; Response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet"; Response.AppendHeader("Content-Type", "text/html; charset=GB2312"); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", fileName)); Response.Charset = "GB2312"; Response.ContentEncoding = Encoding.GetEncoding("GB2312"); Response.BinaryWrite(exportData.GetBuffer()); Response.Flush(); } } /// /// 根據類型獲取實體的描述集合 /// ///類型 private List GetDisplayNames(Type type) { List propertyNames = new List(); if (_propertyNameDic != null && _propertyNameDic.ContainsKey(type)) { propertyNames = _propertyNameDic[type]; } else { var properties = type.GetProperties(); var propertyResult = new List(); propertyNames = GetDisplayNames(properties, out propertyResult); //添加到緩存 if (_propertyNameDic == null) { _propertyNameDic = new Dictionary<Type, List>(); } if (_propertyDic == null) { _propertyDic = new Dictionary<Type, PropertyInfo[]>(); } _propertyNameDic.Add(type, propertyNames); _propertyDic.Add(type, propertyResult.ToArray()); } return propertyNames; } /// /// 獲取屬性描述對應關系 /// ///類型 public List GetMapping(Type type) { List mapping = new List(); if (_displayMappProperty != null && _displayMappProperty.ContainsKey(type)) { mapping = _displayMappProperty[type]; } else { var properties = type.GetProperties(); mapping = GetMapping(properties); //添加到緩存 if (_displayMappProperty == null) { _displayMappProperty = new Dictionary<Type, List>(); } if (_propertyDic == null) { _propertyDic = new Dictionary<Type, PropertyInfo[]>(); } _displayMappProperty.Add(type, mapping); _propertyDic.Add(type, properties); } return mapping; } /// /// 獲取實體的描述集合 /// ///實體屬性組 private List GetDisplayNames(PropertyInfo[] propertyInfos, out List propertyInfoList) { List propertyNames = new List(); propertyInfoList = new List(); if (propertyInfos != null) { for (var i = 0; i < propertyInfos.Length; i++) { //判斷是否是不需要導出的字段 var expoertAttribute = propertyInfos[i].GetCustomAttribute(); if (expoertAttribute == null || expoertAttribute.NeedExport) { var propertyName = propertyInfos[i].GetCustomAttribute(); if (propertyName != null && !string.IsNullOrEmpty(propertyName.DisplayName)) { propertyNames.Add(propertyName.DisplayName); } else { propertyNames.Add(propertyInfos[i].Name); } propertyInfoList.Add(propertyInfos[i]); } } } return propertyNames; } /// /// 獲取實體中的屬性和描述對應關系數據 /// ///屬性集合 private List GetMapping(PropertyInfo[] propertyInfos) { List mapping = new List(); if (propertyInfos != null) { for (var i = 0; i < propertyInfos.Length; i++) { var propertyName = propertyInfos[i].GetCustomAttribute(); if (propertyName != null && !string.IsNullOrEmpty(propertyName.DisplayName)) { mapping.Add(new DisplayMappProperty { Property = propertyInfos[i], DisplayName = propertyName.DisplayName }); } } } return mapping; } /// /// 獲取excel中映射的實體數據 /// /// /// /// /// /// private List GetModel(ISheet sheet, List models, int firstRowNum = 0) where T : new() { //首先獲取excel中的列名 Type type = typeof(T); List mappings = GetMapping(type); int startRow = 0; if (sheet != null) { IRow firstRow = sheet.GetRow(firstRowNum); //一行最后一個cell的編號 即總的列數 int cellCount = firstRow.LastCellNum; var cellValues = new string[cellCount]; //獲取excel中的列名 for (int i = firstRow.FirstCellNum; i < cellCount; i++) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { cellValues[i] = cellValue; } } } //數據開始行 startRow = firstRowNum + 1; //最后一行的標號 int rowCount = sheet.LastRowNum; //讀取數據 for (int i = startRow; i <= rowCount; i++) { var singT = new T(); IRow row = sheet.GetRow(i); if (row == null) continue; //沒有數據的行默認是null        for (int j = row.FirstCellNum; j < cellCount; j++) { //獲取Excel中列名 var cellValue = ""; if (j < cellValues.Length) { cellValue = cellValues[j]; } if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null //給實體賦值 { //根據列名找到對應關系的屬性值 var property = mappings.FirstOrDefault(n => n.DisplayName == cellValue)?.Property; if (property != null) { property.SetValue(singT, row.GetCell(j)?.ToString()); } } } models.Add(singT); } } return models; } } /// /// 將excel轉化為DataTable /// public class ExcelHelper : IDisposable { private string fileName = null; //文件名 private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; public ExcelHelper(string fileName) { this.fileName = fileName; disposed = false; } /// /// 將excel中的數據導入到實體中 /// ///excel工作薄sheet的名稱 ///第一行是否是DataTable的列名 /// 返回的DataTable public DataTable ExcelToDataTable(string sheetName = null, bool isFirstRowColumn = true) { ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最后一列的標號 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //沒有數據的行默認是null        DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (fs != null) fs.Close(); } fs = null; disposed = true; } } } /// /// 屬性描述對應關系 /// public class DisplayMappProperty { /// /// 屬性 /// public PropertyInfo Property { set; get; } /// /// 屬性描述 描述對應excel中的列名 /// public string DisplayName { set; get; } } 調用方法實例,首先是導入,其中ImportModel是excel對應的實體類型: public ActionResult Import(HttpPostedFileBase importFile) { ExcelHelper important = new ExcelHelper(); var agentInfos = important.ExcelToModel(importFile, null, 1); } 導出實例,其中exportModels是需要導出的數據集合: new ExcelHelper.Export(exportModels, Response, "活動分潤", null,null);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM