Search code examples
c#asp.net-coredevexpressspreadsheet

ASP NET CORE MVC - How to binding data to spreadsheet


How to create spreadsheet with data on worksheet from list object ? i using devexpress asp net core to create spreadsheet.

this is my controller:

public ActionResult Overview(IFormFile document)
        {
            var model = new DocumentModel();
            if (document != null)
            {
                //SaveFile(document);
                var stream = new MemoryStream();
                document.CopyTo(stream);

                //Office File API
                var workBook = new Workbook();
                workBook.LoadDocument(stream);
                //preprocess the uploaded file using Spreadsheet Document API

                model.DocumentId = document.FileName;
                model.ContentAccessorByStream = stream;
            }

            return View("Overview", model);
        }

How pass list to spreadsheet ?


Solution

  • You can try to import your list with data into a worksheet:

    // Import the list into the worksheet.
    // Data starts with the B3 cell.
    workbook.Worksheets[0].Import(yourList, 2, 1);
    

    ...or use Data Binding:

    private void BindToRange(List<MyObject> dataSource, CellRange 
        bindingRange, Worksheet sheet) {
    
        // Specify the binding options.
        ExternalDataSourceOptions dsOptions = new ExternalDataSourceOptions();
        dsOptions.ImportHeaders = true;
        dsOptions.CellValueConverter = new MyObjectConverter();
        dsOptions.SkipHiddenRows = true;
    
        // Bind the data source to the worksheet range.
        WorksheetDataBinding sheetDataBinding = sheet.DataBindings.BindToDataSource(dataSource, bindingRange, dsOptions);
    
        // Adjust the column width.
        sheetDataBinding.Range.AutoFitColumns();
    }
    

    Please refer to the following articles to learn more info: