主代码在这:
黑人老外写的代码,条理很清晰。
↓ 用法:(由于我直接就是用List泛型集合,就不新定义一个集合对象了,所以封装了下:)
private void Export2Excel(IEnumerable pValues) where T : class{ var saveE = new ExportToExcel >(); saveE.DataToPrint = pValues.ToList(); saveE.GenerateReport();}
↓ 稍微封装下,用起来就更简单了,一句就完了
//比如,我有个音乐集合//ListsourcesExport2Excel(sources);
看起来真的好爽,一句就完了,贴一下老外的代码吧。
//ExportToExcels = new ExportToExcel (); //ICollectionView view = CollectionViewSource.GetDefaultView(dgBook.ItemsSource); //s.DataToPrint = (Books)view.SourceCollection; //s.GenerateReport(); /// /// 导出 Excel 类,(带示例) /// ////// public class ExportToExcel where T : class where U : List { public List DataToPrint; // Excel 对象实例. private Excel.Application _excelApp = null; private Excel.Workbooks _books = null; private Excel._Workbook _book = null; private Excel.Sheets _sheets = null; private Excel._Worksheet _sheet = null; private Excel.Range _range = null; private Excel.Font _font = null; // 可选 参数 private object _optionalValue = Missing.Value; /// /// 生成报表,和其他功能 /// public void GenerateReport() { try { if (DataToPrint != null) { if (DataToPrint.Count != 0) { Mouse.SetCursor(Cursors.Wait); CreateExcelRef(); FillSheet(); OpenReport(); Mouse.SetCursor(Cursors.Arrow); } } } catch (Exception e) { MessageBox.Show("Excel导出失败!\n", e.Message); } finally { ReleaseObject(_sheet); ReleaseObject(_sheets); ReleaseObject(_book); ReleaseObject(_books); ReleaseObject(_excelApp); } } ////// 展示 Excel 程序 /// private void OpenReport() { _excelApp.Visible = true; } ////// 填充 Excel sheet /// private void FillSheet() { object[] header = CreateHeader(); WriteData(header); } ////// 将数据写入 Excel sheet /// /// private void WriteData(object[] header) { object[,] objData = new object[DataToPrint.Count, header.Length]; for (int j = 0; j < DataToPrint.Count; j++) { var item = DataToPrint[j]; for (int i = 0; i < header.Length; i++) { var y = typeof(T).InvokeMember(header[i].ToString(), BindingFlags.GetProperty, null, item, null); objData[j, i] = (y == null) ? "" : y.ToString(); } } AddExcelRows("A2", DataToPrint.Count, header.Length, objData); AutoFitColumns("A1", DataToPrint.Count + 1, header.Length); } ////// 根据数据拟合 列 /// /// /// /// private void AutoFitColumns(string startRange, int rowCount, int colCount) { _range = _sheet.get_Range(startRange, _optionalValue); _range = _range.get_Resize(rowCount, colCount); _range.Columns.AutoFit(); } ////// 根据属性名创建列标题 /// ///private object[] CreateHeader() { PropertyInfo[] headerInfo = typeof(T).GetProperties(); // 为 标头 创建 Array // 开始从 A1 处添加 List