Converting between Excel and HTML formats is a common task for developers working on data visualization, reporting, or web-based applications. Excel files are often used to store, organize, and analyze structured data, while HTML is widely used to display information on the web. Converting between these two formats allows seamless integration between back-end data processing and front-end data presentation. In this article, we will demonstrate how to convert Excel files to HTML format and HTML files to Excel format in React using Spire.XLS for JavaScript.
Install Spire.XLS for JavaScript
To get started with converting Excel to PDF in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:
npm i spire.xls
Make sure to copy all the dependencies to the public folder of your project.
For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project
Convert Excel to HTML in React
Spire.XLS for JavaScript provides the Worksheet.SaveToHtml() function, which enables you to save a specific worksheet in an Excel file as an HTML file. The key steps for converting an Excel worksheet to HTML using Spire.XLS for JavaScript are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() function.
- Load the Excel file using the Workbook.LoadFromFile() function.
- Get a specific worksheet using the Workbook.Worksheets.get(index) function.
- Create an HTMLOptions object using the wasmModule.HTMLOptions.Create() function.
- Set the HTMLOptions.ImageEmbedded property as "true" to embed images in the converted HTML file.
- Save the worksheet as an HTML file using the Worksheet.SaveToHtml() function.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to hold the loaded WASM module const [wasmModule, setWasmModule] = useState(null); // useEffect hook to load the WASM module when the component mounts useEffect(() => { const loadWasm = async () => { try { // Access the Module and spirexls from the global window object const { Module, spirexls } = window; // Set the wasmModule state when the runtime is initialized Module.onRuntimeInitialized = () => { setWasmModule(spirexls); }; } catch (err) { // Log any errors that occur during loading console.error('Failed to load WASM module:', err); } }; // Create a script element to load the WASM JavaScript file const script = document.createElement('script'); script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`; script.onload = loadWasm; // Append the script to the document body document.body.appendChild(script); // Cleanup function to remove the script when the component unmounts return () => { document.body.removeChild(script); }; }, []); // Function to convert an Excel worksheet to HTML const ExcelToHTML = async () => { if (wasmModule) { // Load the input file into the virtual file system (VFS) const inputFileName = 'Sample.xlsx'; await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create a new workbook const workbook = wasmModule.Workbook.Create(); // Load an existing Excel document workbook.LoadFromFile({fileName: inputFileName}); // Get the first worksheet let sheet = workbook.Worksheets.get(0); // Create an HTMLOptions object let options = wasmModule.HTMLOptions.Create(); // Embed images in the converted HTML file options.ImageEmbedded = true; // Specify the output HTML file path const outputFileName = 'ToHtml.html'; // Save the worksheet to HTML with the images embedded sheet.SaveToHtml({fileName:outputFileName, saveOption:options}); // Read the saved file and convert it to a Blob object const modifiedFileArray = wasmModule.FS.readFile(outputFileName); const modifiedFile = new Blob([modifiedFileArray], { type: 'text/html' }); // Create a URL for the Blob and initiate the download const url = URL.createObjectURL(modifiedFile); const a = document.createElement('a'); a.href = url; a.download = outputFileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); // Clean up resources used by the workbook workbook.Dispose(); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Convert an Excel Worksheet to HTML Using JavaScript in React</h1> <button onClick={ExcelToHTML} disabled={!wasmModule}> Convert </button> </div> ); } export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to convert the specified Excel worksheet to HTML format:
The below screenshot shows the input Excel worksheet and the converted HTML file:
Convert HTML to Excel in React
Spire.XLS for JavaScript offers the Workbook.LoadFromHtml() function for loading an HTML file. Once the HTML file is loaded, you can save it as an Excel file using the Workbook.SaveToFile() function. The key steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() function.
- Load the HTML file using the Workbook.LoadFromHtml() function.
- Save the HTML file to an Excel file using the Workbook.SaveToFile() function.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to hold the loaded WASM module const [wasmModule, setWasmModule] = useState(null); // useEffect hook to load the WASM module when the component mounts useEffect(() => { const loadWasm = async () => { try { // Access the Module and spirexls from the global window object const { Module, spirexls } = window; // Set the wasmModule state when the runtime is initialized Module.onRuntimeInitialized = () => { setWasmModule(spirexls); }; } catch (err) { // Log any errors that occur during loading console.error('Failed to load WASM module:', err); } }; // Create a script element to load the WASM JavaScript file const script = document.createElement('script'); script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`; script.onload = loadWasm; // Append the script to the document body document.body.appendChild(script); // Cleanup function to remove the script when the component unmounts return () => { document.body.removeChild(script); }; }, []); // Function to convert an HTML to Excel const HTMLToExcel = async () => { if (wasmModule) { // Load the input file into the virtual file system (VFS) const inputFileName = 'HtmlSample.html'; await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create a new workbook const workbook = wasmModule.Workbook.Create(); // Load an existing HTML file workbook.LoadFromHtml({fileName: inputFileName}); // Specify the output Excel file path const outputFileName = 'ToExcel.xlsx'; // Save the HTML file to Excel format workbook.SaveToFile({fileName:outputFileName,version:wasmModule.ExcelVersion.Version2013}); // Read the saved file and convert it to a Blob object const modifiedFileArray = wasmModule.FS.readFile(outputFileName); const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); // Create a URL for the Blob and initiate the download const url = URL.createObjectURL(modifiedFile); const a = document.createElement('a'); a.href = url; a.download = outputFileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); // Clean up resources used by the workbook workbook.Dispose(); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Convert an HTML File to Excel Using JavaScript in React</h1> <button onClick={HTMLToExcel} disabled={!wasmModule}> Convert </button> </div> ); } export default App;
Get a Free License
To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.