注释: 使用Window自带的 Microsoft.Office.Interop.Excel; 类库实现
具体代码如下:
/// <summary> /// 导出Excel类 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// public class ImportFromExcel<T, U> where T : class, new() where U : List<T>, new() /// public class ExportToExcel<T, U> where T : class where U : List<T> public class ExcelHelper<T, U> where T : class, new() where U : List<T>, new() { #region 对象数据 导出为Excel /// <summary> /// 数据集 /// </summary> public List<T> LstTMdl { get; set; } // 可选 参数 private object _missingValue = Missing.Value; /// <summary> /// 生成Excel报表 /// </summary> /// <param name="excelFullName">Excel全路径</param> /// <returns></returns> public bool ExportObjectsToExcel(string excelFullName) { bool isSuccess = false; Application excelApp = null; //Microsoft.Office.Interop.Excel.Application Workbooks books = null; _Workbook book = null; Sheets sheets = null; _Worksheet workSheet = null; try { if (LstTMdl != null) { // 创建 Excel 传递的参数实例 excelApp = new Application(); excelApp.DisplayAlerts = false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 books = excelApp.Workbooks; book = books.Add(_missingValue); sheets = book.Worksheets; workSheet = (_Worksheet)(sheets.get_Item(1)); //Excel sheet 索引从1开始 // 存在数据则输出(填充 Excel sheet) if (LstTMdl.Count != 0) { //根据属性名创建列标题 PropertyInfo[] propertyInfo = typeof(T).GetProperties(); // 为标头创建Array object[] arrExcelFileds = GetExcelFiledsName(propertyInfo); //开始从 A1 处添加 AddExcelRows(workSheet, "A1", 1, arrExcelFileds.Length, arrExcelFileds); //将数据写入 Excel sheet object[,] cellsContent = GetExcelCellsContent(arrExcelFileds); AddExcelRows(workSheet, "A2", LstTMdl.Count, arrExcelFileds.Length, cellsContent); // 根据数据拟合列 AutoFitColumns(workSheet, "A1", LstTMdl.Count + 1, arrExcelFileds.Length); } //excelApp.Visible = true;//展示 Excel 程序 book.SaveAs(excelFullName);//直接保存Excel文件(不打开) isSuccess = true; } book.Close(); excelApp.Quit(); } catch (Exception ex) { isSuccess = false; } finally { ReleaseObject(workSheet); ReleaseObject(sheets); ReleaseObject(book); ReleaseObject(books); ReleaseObject(excelApp); } return isSuccess; } /// <summary> /// 获取Excel各单元格内容 /// </summary> /// <param name="arrExcelFileds"></param> /// <returns></returns> private object[,] GetExcelCellsContent(object[] arrExcelFileds) { object[,] cellsContent = new object[LstTMdl.Count, arrExcelFileds.Length]; for (int j = 0; j < LstTMdl.Count; j++) { var item = LstTMdl[j]; for (int i = 0; i < arrExcelFileds.Length; i++) { var y = typeof(T).InvokeMember(arrExcelFileds[i].ToString(), BindingFlags.GetProperty, null, item, null); cellsContent[j, i] = (y == null) ? "" : y.ToString(); } } return cellsContent; } /// <summary> /// 获取Excel列头名称 /// </summary> /// <param name="propertyInfo"></param> /// <returns></returns> private object[] GetExcelFiledsName(PropertyInfo[] propertyInfo) { List<object> objHeaders = new List<object>(); for (int n = 0; n < propertyInfo.Length; n++) { objHeaders.Add(propertyInfo[n].Name); } var arrExcelFileds = objHeaders.ToArray(); return arrExcelFileds; } /// <summary> /// 添加行数据 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> /// <param name="values"></param> /// <param name="numberFormatLocal">默认值 "@" :单元格格式为文本</param> private void AddExcelRows(_Worksheet workSheet, string startCell, int rowCount, int colCount, object values, string numberFormatLocal, bool isFontBold = false) { Range range = workSheet.get_Range(startCell, _missingValue); range = range.get_Resize(rowCount, colCount); range.Columns.AutoFit(); // 设置列宽为自动适应 range.NumberFormatLocal = numberFormatLocal; //设置单元格格式. "@":为文本 Font font = range.Font; font.Bold = isFontBold; range.set_Value(_missingValue, values); } /// <summary> /// 添加行数据 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> /// <param name="values"></param> private void AddExcelRows(_Worksheet workSheet, string startCell, int rowCount, int colCount, object values) { AddExcelRows(workSheet, startCell, rowCount, colCount, values, "@"); } /// <summary> /// 添加行数据 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> /// <param name="values"></param> private void AddExcelFiledTitles(_Worksheet workSheet, string startCell, int rowCount, int colCount, object values) { // 列标题设置为加粗字体 AddExcelRows(workSheet, startCell, rowCount, colCount, values, "@", true); } /// <summary> /// 根据数据拟合列 /// </summary> /// <param name="startCell"></param> /// <param name="rowCount"></param> /// <param name="colCount"></param> private void AutoFitColumns(_Worksheet workSheet, string startCell, int rowCount, int colCount) { Range range = workSheet.get_Range(startCell, _missingValue); range = range.get_Resize(rowCount, colCount); range.Columns.AutoFit(); } #endregion #region 读取Excel文件内数据 为对象 ///// <summary> ///// 导出Excel类 ///// </summary> ///// <typeparam name="T"></typeparam> ///// <typeparam name="U"></typeparam> //public class ImportFromExcel<T, U> where T : class, new() where U : List<T>, new() //{ /// <summary> /// 读Excel表内容 /// </summary> /// <returns></returns> public U ReadExcelData(string excelFullName) { U lstData = new U(); Application excelApp = new Application(); //excelApp.Visible = false; //excelApp.UserControl = true; _Workbook book = excelApp.Application.Workbooks.Open(excelFullName); _Worksheet sheet = (_Worksheet)(book.Worksheets.get_Item(1)); try { int rowsCount = sheet.UsedRange.Rows.Count; // sheet.UsedRange.Cells.Rows.Count;//行数 int columnsCount = sheet.UsedRange.Columns.Count; // sheet.UsedRange.Cells.Columns.Count; //列数 //列头 PropertyInfo[] headerInfo = typeof(T).GetProperties(); Dictionary<PropertyInfo, int> keyValuePairs = new Dictionary<PropertyInfo, int>(); for (int i = 1; i <= columnsCount; i++) { var value = sheet.Cells[1, i].Value2.ToString(); //取单元格值 var propertyInfo = headerInfo.Where(pInfo => pInfo.Name == value).FirstOrDefault(); if (propertyInfo != null) { keyValuePairs.Add(propertyInfo, i); } } //内容 for (int j = 2; j <= rowsCount; j++) { T instance = new T(); foreach (var keyValue in keyValuePairs) { var propertyInfo = keyValue.Key; var propertyValue = sheet.Cells[j, keyValue.Value].Value2.ToString(); //取单元格值 ReflectionHelper.SetInstancePropertyValue(instance, propertyInfo, propertyValue); } lstData.Add(instance); } } catch (Exception ex) { lstData = null; //LogHelper.Instance.Error("" + ex.ToString()); } finally { book?.Close(); excelApp?.Quit(); ReleaseObject(sheet); ReleaseObject(book); ReleaseObject(excelApp); } return lstData; } //} #endregion #region 公共 /// <summary> /// 释放未使用的对象 /// </summary> /// <param name="obj"></param> private void ReleaseObject(object obj) { try { if (obj != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } } catch (Exception ex) { obj = null; } finally { GC.Collect(); } } #endregion }