Proper data formatting is essential for accurate calculations, sorting, and analysis. In Excel, numbers are sometimes mistakenly stored as text, which prevents them from being used in mathematical calculations. On the other hand, certain values like ZIP codes, phone numbers, and product IDs should be stored as text to preserve leading zeros and ensure consistency. Knowing how to convert between text and numeric formats is essential for maintaining data integrity, preventing errors, and improving usability. In this article, you will learn how to convert text to numbers and numbers to text in Excel in React using Spire.XLS for JavaScript.
Install Spire.XLS for JavaScript
To get started with converting text to numbers and numbers to text in Excel 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
After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files 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 Text to Numbers in Excel
With Spire.XLS for JavaScript, developers can format the text in individual cells or a range of cells as numbers using the CellRange.ConvertToNumber() method. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load the Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet using the Workbook.Worksheets.get(index) method.
- Get the desired cell or range of cells using the Worksheet.Range.get() method.
- Format the text in the cell or range of cells as numbers using the CellRange.ConvertToNumber() method.
- Save the resulting workbook using the Workbook.SaveToFile() method.
- 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 text to numbers in an Excel worksheet const ConvertTextToNumbers = async () => { if (wasmModule) { // Load the sample Excel file into the virtual file system (VFS) let excelFileName = 'TextToNumbers_Input.xlsx'; await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`); // Create a new workbook const workbook = wasmModule.Workbook.Create(); // Load the Excel file from the virtual file system workbook.LoadFromFile(excelFileName); // Get the first worksheet let sheet = workbook.Worksheets.get(0); // Get the desired cell range let range = sheet.Range.get("D2:D6"); // Convert the text in the cell range as numbers range.ConvertToNumber(); // Define the output file name const outputFileName = "TextToNumbers_output.xlsx"; // Save the workbook to the specified path workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2010 }); // 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 Text to Numbers in Excel Using JavaScript in React</h1> <button onClick={ConvertTextToNumbers} 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 format text stored in specific cells of an Excel worksheet as numbers:
The screenshot below shows the input Excel worksheet and the output Excel worksheet:
Convert Numbers to Text in Excel
To convert numbers stored in specific cells or a range of cells as text, developers can use the CellRange.NumberFormat property. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load the Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet using the Workbook.Worksheets.get(index) method.
- Get the desired cell or range of cells using the Worksheet.Range.get() method.
- Format the numbers in the cell or range of cells as text by setting the CellRange.NumberFormat property to "@".
- Save the resulting workbook using the Workbook.SaveToFile() method.
- 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 numbers to text in an Excel worksheet const ConvertNumbersToText = async () => { if (wasmModule) { // Load the sample Excel file into the virtual file system (VFS) let excelFileName = 'NumbersToText_Input.xlsx'; await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`); // Create a new workbook const workbook = wasmModule.Workbook.Create(); // Load the Excel file from the virtual file system workbook.LoadFromFile(excelFileName); // Get the first worksheet let sheet = workbook.Worksheets.get(0); // Get the desired cell range let range = sheet.Range.get("F2:F9"); // Convert the numbers in the cell range as text range.NumberFormat = "@" // Define the output file name const outputFileName = "NumbersToText_output.xlsx"; // Save the workbook to the specified path workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2010 }); // 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 Numbers To Text in Excel Using JavaScript in React</h1> <button onClick={ConvertNumbersToText} 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.