When working with Excel workbooks in SpreadJS, sometimes only one sheet from a workbook is relevant to your application and what your users are focusing on. In this case, you can use a hidden workbook to load the entire Excel workbook, and then get one of the sheets out of that workbook for your users to interact with.
In this post, I’ll show you how to accomplish that using the client-side ExcelIO library and two instances of Spread.Sheets on a page:
- a hidden one for loading the workbook
- the other for displaying the selected sheet
Set up the project
You can follow along and create your own project, or use my sample project: SJS Single Sheet Loading Sample.zip
To start using Spread.Sheets, add the main JS library and CSS files in the head section of your HTML file. In this case we are also loading an Excel file, so we also need to add the JS library for Client-Side ExcelIO:
If you are deploying your page, you also need to add your license key to the head section:
To finish the setup, add two DIV elements to the body to host the Spread.Sheets instances:
- the hidden one (display:none) to hold the workbook
- the visible instance to show a sheet
Then we can add some code to the script to initialize those two instances as well as the Client-Side ExcelIO:
Add ExcelIO Code
In this page, we add code to let the user select the workbook that they want to get a sheet from. To do this we can add some HTML inputs:
For the button to actually start loading the Excel file, we can write a function called ImportFileStart to get the Excel file from the input element and load its JSON into the hidden workbook:
In this application, we add a drop-down menu that shows up after a user loads a workbook so they can look at a specific sheet. To do this, we add some HTML elements to the page and create a function in the script called CreateSheetSelect.
Now we can call the CreateSheetSelect function in the ImportFileStart function, just after the hiddenWorkbook.fromJSON(workbookObj);
line.
When the user selects a workbook to load, the drop-down menu shows up with a list of sheets they can load in the visible Spread.Sheets instance.
Now we implement a function called CopySheet that fires when the user changes the selection. This function loads the Sheet from the workbook at the specified sheet index. However, we also need to get the styles from the original workbook and add them to the new workbook, since we are only loading one sheet:
After that code is added, you can now load a single sheet from an Excel workbook into Spread.Sheets.
What's next? If you don't already have it, Download a Free Trial of SpreadJS.