Пример #1
0
        internal byte[] ObjectToExcelBytes(ExcelModel excel, ExcelExporterOptions options)
        {
            ExcelType excelType = options.ExcelType;
            var       workbook  = Workbook(excelType);

            CheckExcelModel(excel);
            foreach (var excelSheet in excel.Sheets)
            {
                var sheet = string.IsNullOrWhiteSpace(excelSheet.Title)
                    ? workbook.CreateSheet()
                    : workbook.CreateSheet(excelSheet.Title);
                sheet.ForceFormulaRecalculation = true;
                var columns = excelSheet.Columns.OrderBy(c => c.Order).ToArray();
                for (var i = 0; i < columns.Length; i++)
                {
                    sheet.SetColumnWidth(i, 16 * 256);
                    // todo 此处可统计字节数Min(50,Max(16,标题与内容最大长))
                }
                var headerRow = sheet.CreateRow(0);
                for (var i = 0; i < columns.Length; i++)
                {
                    var cell = headerRow.CreateCell(i);
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(columns[i].Title);
                }
                var columnTitles = columns.Select(c => c.Title).ToArray();
                var rowNumber    = 1;
                var data         = excelSheet.Rows;
                foreach (var item in data)
                {
                    var row = sheet.CreateRow(rowNumber++);
                    for (var i = 0; i < columns.Length; i++)
                    {
                        var column = columns[i];
                        var cell   = row.CreateCell(i);
                        var val    = item.ContainsKey(column.Title)?(item?[column.Title] ?? "").ToString() : "";
                        SetCellValue(excelType, column, cell, val, columnTitles);
                    }
                }
            }

            return(ToBytes(workbook));
        }
Пример #2
0
 private void CheckExcelModel(ExcelModel excel)
 {
     //todo validate
 }