예제 #1
0
        public static byte[] CreateExcel <T>(IEnumerable <T> items, Action <ArrayToExcelScheme <T> > schemeBuilder = null)
        {
            var scheme = new ArrayToExcelScheme <T>();

            schemeBuilder?.Invoke(scheme);
            return(_createExcel(items, scheme));
        }
예제 #2
0
        static byte[] _createExcel <T>(IEnumerable <T> items, ArrayToExcelScheme <T> scheme)
        {
            using (var ms = new MemoryStream())
            {
                using (var document = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook))
                {
                    var workbookpart = document.AddWorkbookPart();
                    workbookpart.Workbook = new Workbook();

                    var worksheetPart = workbookpart.AddNewPart <WorksheetPart>();
                    worksheetPart.Worksheet = new Worksheet();

                    var sheets = document.WorkbookPart.Workbook.AppendChild(new Sheets());
                    sheets.Append(new Sheet()
                    {
                        Id      = document.WorkbookPart.GetIdOfPart(worksheetPart),
                        SheetId = 1,
                        Name    = _normSheetName(scheme.SheetName) ?? "Sheet1"
                    });

                    _addStyles(document);

                    if (scheme.Columns.Count > 0)
                    {
                        var cols = worksheetPart.Worksheet.AppendChild(new Columns());
                        cols.Append(scheme.Columns.Select(x => new Column()
                        {
                            Min = (uint)(x.Index + 1), Max = (uint)(x.Index + 1), Width = x.Width, CustomWidth = true, BestFit = true
                        }));

                        var rows      = _getRows(items, scheme.Columns);
                        var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
                        sheetData.Append(rows);

                        worksheetPart.Worksheet.Append(new AutoFilter()
                        {
                            Reference = $"A1:{_getColReference(scheme.Columns.Count - 1)}{rows.Length}"
                        });
                    }

                    workbookpart.Workbook.Save();
                }
                return(ms.ToArray());
            }
        }