SpreadJS - How to get the data source for a table?

Posted by: finance on 9 January 2025, 6:33 pm EST

    • Post Options:
    • Link

    Posted 9 January 2025, 6:33 pm EST

    In my React project, I use SpreadJS table like shown below -

    const sheet = workbook.getActiveSheet()
    const table = sheet.tables.addFromDataSource(
        'table',
        0,
        0,
        dataWithSelectedColumns,  // this is a json object, which I later want to export
        tableTheme,
        {
            showFooter: false,
            showHeader: true,
            showResizeHandle: true,
        }
    )

    Although I don’t keep “dataWithSelectedColumns” in state, I do hold the spread instance in a ref variable, and I would like to get back the data source from the table. How can I do that? I have tried using toJSON( { includeBindingSource: true }), but it has a lot of metadata, and I’d have to transform the code to obtain the original data source.

    Is there a faster, simpler way to achieve this?

    Thank you!

  • Posted 10 January 2025, 7:17 am EST

    Hi,

    It seems you are trying to retrieve the dataSource that was added to a table within the SpreadJS instance.

    This can be achieved by accessing the table via the Spread instance and then extracting its data. Below is a code snippet demonstrating how this can be implemented:

    // Get the table object from the active sheet
    var tableFromCurrentSpreadRef = spread.getActiveSheet().tables.findByName("Table1");
    
    // Retrieve the table's range
    var tableRange = tableFromCurrentSpreadRef.range();
    
    // Extract the data within the table's range
    var data = spread
        .getActiveSheet()
        .getArray(tableRange.row, tableRange.col, tableRange.rowCount, tableRange.colCount);
    
    // Retrieve the table's column metadata
    var columns = tableFromCurrentSpreadRef.toJSON().columns;
    
    // Map the table data into an object array
    console.log(mapToObjectArray(data, columns));
    
    
    function mapToObjectArray(data, columns) {
        const header = data[0]; // First row as the header
        const rows = data.slice(1); // Remaining rows as data
    
        return rows.map(row => {
            const obj = {};
            columns.forEach((column, index) => {
                obj[column.dataField] = row[index];
            });
            return obj;
        });
    }

    Refer to the attached sample: Sample (8).zip

    References:

    SpreadJS API Documentation - getArray Method: https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#getarray)

    Please let us know if this addresses your requirements or if you need further assistance.

    Best regards,

  • Posted 10 January 2025, 7:53 pm EST

    Thank you! This works like a charm!

Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels