Aspose.Cells List to Excel

        internal static MemoryStream Export<T>(List<T> query, string name)
        {
            SetLicense();
            using (var workbook = new Workbook())
            {
                Worksheet worksheet;
                if (workbook.Worksheets.Count > 0)
                {
                    worksheet = workbook.Worksheets[0];
                    worksheet.Name = name;
                }
                else
                {
                    worksheet = workbook.Worksheets.Add(name);
                }
                var ps = typeof(T).GetPublicProperties(System.ComponentModel.BrowsableAttribute.No);
                if (ps!=null)
                {
                    // For first row name
                    for (int j = 0; j < ps.Count; j++)
                    {
                        worksheet.Cells[0,j].PutValue(ps[j].GetDisplayName());
                    }
                    // Log every cell in the list for one by one
                    for (int i = 0; i < query.Count; i++)
                    {
                        for (int j = 0; j < ps.Count; j++)
                        {
                            worksheet.Cells[i + 1,j].PutValue(ps[j].GetValue(query[i]));
                        }
                    }
                }
                worksheet.AutoFitColumns();
                MemoryStream memoryStream = new MemoryStream();
                workbook.Save(memoryStream, SaveFormat.Xlsx);
                memoryStream.Seek(0, SeekOrigin.Begin);
                return memoryStream;
            }
        }

 

posted @ 2020-07-31 16:59  devs  阅读(288)  评论(0编辑  收藏  举报