使用Teleri 导出实体类数组到Excel
使用Teleri 导出实体类数组到Excel:
首先引用相应的Telerik库。
实体类 example:
1 public partial class Product 2 { 3 4 5 public int Id { get; set; } 6 public string Product_name { get; set; } 7 public string Brand { get; set; } 8 public string Model { get; set; } 9 public int Product_Type_Id { get; set; } 10 public string Description { get; set; } 11 public string Account_Code { get; set; } 12 public string eProcure_id { get; set; } 13 public Nullable<bool> Can_Purchase { get; set; } 14 public string UserStamp { get; set; } 15 16 }
工具类:ExportXlsxHelper
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using Telerik.Windows.Documents.Spreadsheet.Core; 6 using Telerik.Windows.Documents; 7 using Telerik.Windows.Documents.Spreadsheet.Model; 8 9 using System.IO; 10 using Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml.Xlsx; 11 12 namespace AssetAdmin.Utils 13 { 14 public class ExportXlsxHelper 15 { 16 public static void ExportXlsx(Object[] os, string filename) 17 { 18 19 Workbook wb = new Workbook(); 20 Worksheet ws = wb.Worksheets.Add(); 21 if (os.Length < 1) 22 { 23 return; 24 } 25 for (var j = 0; j < os[0].GetType().GetProperties().Length; j++) 26 { 27 ws.Cells[0, j].SetValue(os[0].GetType().GetProperties()[j].Name); 28 } 29 for (var i = 0; i < (os.Length);i++ ) 30 { 31 for (var j = 0; j < os[i].GetType().GetProperties().Length; j++) 32 { 33 ws.Cells[i + 1, j].SetValue(os[i].GetType().GetProperties()[j].GetValue(os[i])==null?" ":os[i].GetType().GetProperties()[j].GetValue(os[i]).ToString()); 34 } 35 } 37 Telerik.Windows.Documents.Spreadsheet.FormatProviders.IWorkbookFormatProvider formatProvider = new XlsxFormatProvider(); 38 39 using (FileStream output = new FileStream(filename, FileMode.Create)) 40 { 41 formatProvider.Export(wb, output); 42 } 43 } 44 } 45 }