Conversion (6)
Convert Text to Numbers or Numbers to Text in Excel with JavaScript in React
2025-02-17 03:12:47 Written by KoohjiProper 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.
Convert Excel to OpenXML and OpenXML to Excel with JavaScript in React
2025-02-10 01:05:26 Written by KoohjiOpenXML is a widely used format for creating and manipulating Microsoft Office documents, including Excel files. It provides a structured, XML-based representation of spreadsheet data, making it ideal for interoperability and automation. Converting an Excel file to OpenXML allows users to extract and process data programmatically, while converting OpenXML back to Excel ensures compatibility with Microsoft Excel and other spreadsheet applications. This article will guide you through the process of converting Excel to OpenXML and OpenXML back to Excel in React using Spire.XLS for JavaScript.
Install Spire.XLS for JavaScript
To get started with converting Excel to OpenXML and OpenXML to Excel in a React application, you can either download Spire.XLS for JavaScript from the official 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. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project.
Convert Excel to OpenXML with JavaScript
Converting an Excel workbook to OpenXML format can be easily achieved using the Workbook.SaveAsXml() method provided by Spire.XLS for JavaScript. Below are the key steps:
- Load the font file to ensure correct text rendering.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load the Excel file using the Workbook.LoadFromFile() method.
- Save the Excel file as an OpenXML file using the Workbook.SaveAsXml() method.
Code example:
- 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 Excel to OpenXML
const ExcelToOpenXML = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input file into the virtual file system (VFS)
const inputFileName = 'Sample.xlsx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Specify the output OpenXML file path
const outputFileName = 'ExcelXML.xml';
// Create a new workbook
const workbook = wasmModule.Workbook.Create();
// Load an existing Excel document
workbook.LoadFromFile({ fileName: inputFileName });
// Save the workbook as an OpenXML file
workbook.SaveAsXml({ fileName: outputFileName });
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/xml' });
// 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 File to OpenXML Using JavaScript in React</h1>
<button onClick={ExcelToOpenXML} 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 save the Excel file as an OpenXML file:

The below screenshot shows the input Excel file and the converted OpenXML file:

Convert OpenXML to Excel with JavaScript
To convert an OpenXML file back to Excel, you can use the Workbook.LoadFromXml() method to load the OpenXML file and the Workbook.SaveToFile() method to save it in Excel format. Below are the key steps:
- Load the font file to ensure correct text rendering.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Read an OpenXML file into a stream using the wasmModule.Stream.CreateByFile() method.
- Load the OpenXML file from the stream using the Workbook.LoadFromXml() method.
- Save the OpenXML file as an Excel file using the Workbook.SaveToFile() method.
Code example:
- 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 OpenXML to Excel
const OpenXMLToExcel = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input file into the virtual file system (VFS)
const inputFileName = 'ExcelToXML.xml';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Specify the output Excel file path
const outputFileName = 'XMLToExcel.xlsx';
// Create a new workbook
const workbook = wasmModule.Workbook.Create();
// Read an OpenXML file into a stream
let fileStream = wasmModule.Stream.CreateByFile(inputFileName);
// Load the OpenXML file from the stream
workbook.LoadFromXml({ stream: fileStream });
// Save the OpenXML file as an Excel file
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 OpenXML File to Excel Using JavaScript in React</h1>
<button onClick={OpenXMLToExcel} 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.
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.
Converting files between Excel and CSV formats is a highly common and essential task in data processing. Excel is ideal for data organization, analysis, and visualization, while CSV (Comma-Separated Values) files are lightweight and compatible with various applications, making them ideal for data exchange. Whether you're preparing data for analysis, sharing information between systems, or ensuring seamless compatibility with other software, the ability to efficiently switch between these two formats greatly enhances the convenience and flexibility of data processing tasks. In this article, we will demonstrate how to convert Excel to CSV and CSV to Excel in React using Spire.XLS for JavaScript.
Install Spire.XLS for JavaScript
To get started with converting between Excel and CSV files 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 CSV with JavaScript in React
Spire.XLS for JavaScript provides the Worksheet.SaveToFile() function, which enables developers to save a specific worksheet in a workbook as a standalone CSV file. The key steps for converting an Excel worksheet to CSV 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.
- Save the worksheet in CSV format using the Worksheet.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 Excel worksheet to CSV
const ExcelToCSV = 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);
// Specify the output CSV file path
const outputFileName = 'ExcelToCSV.csv';
//Save the worksheet to CSV
sheet.SaveToFile({fileName:outputFileName, separator:",", encoding:wasmModule.Encoding.get_UTF8()});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'text/csv'});
// 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 CSV Using JavaScript in React</h1>
<button onClick={ExcelToCSV} 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 CSV:

The below screenshot shows the input Excel worksheet and the converted CSV:

Convert CSV to Excel with JavaScript in React
The Workbook.LoadFromFile() function in Spire.XLS for JavaScript can also be used for loading CSV files. Once a CSV file is loaded, it can be saved as an Excel file using the Workbook.SaveToFile() function. The key steps for converting a CSV file to Excel using Spire.XLS for JavaScript are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() function.
- Load the CSV file using the Workbook.LoadFromFile() function.
- Get a specific worksheet using the Workbook.Worksheets.get(index) function.
- Ignore possible errors while saving the numbers in a specific cell range of the worksheet as text using the CellRange.IgnoreErrorOptions property.
- Autofit columns using the CellRange.AutoFitColumns() function.
- Save the CSV file in Excel format 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 a CSV file to Excel
const CSVToExcel = async () => {
if (wasmModule) {
// Load the input file into the virtual file system (VFS)
const inputFileName = 'Sample.csv';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a new workbook
const workbook = wasmModule.Workbook.Create();
// Load an existing CSV file
workbook.LoadFromFile({ fileName: inputFileName, separator: ",", row: 1, column: 1 });
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Ignore possible errors when saving numbers as text during the conversion
sheet.Range.get("A1:E7").IgnoreErrorOptions = wasmModule.IgnoreErrorType.NumberAsText;
// Auto-fit columns in the used range of the worksheet
sheet.AllocatedRange.AutoFitColumns();
// Specify the output Excel file path
const outputFileName = 'CSVToExcel.xlsx';
// Save the modified 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 a CSV File to Excel Using JavaScript in React</h1>
<button onClick={CSVToExcel} 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.
Converting Excel worksheets into image formats like PNG or JPEG can be useful for sharing spreadsheet data in presentations, reports, or other documents. Unlike Excel files, image formats ensure that the formatting and structure remain consistent, regardless of the viewer’s software or platform. In this article, we will demonstrate how to convert Excel to images in React using Spire.XLS for JavaScript.
- Convert an Excel Worksheet to an Image
- Convert an Excel Worksheet to an Image without White Margins
- Convert a Specific Cell Range to an Image
Install Spire.XLS for JavaScript
To get started with converting Excel to images 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. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project.
Convert an Excel Worksheet to an Image with JavaScript in React
Spire.XLS for JavaScript allows you to convert a worksheet into an image using the Worksheet.ToImage() function. Once the conversion is complete, you can save the image in formats such as PNG, JPG, or BMP with the Image.Save() function. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Convert the worksheet to an image using the Worksheet.ToImage() function.
- Save the image to a PNG file using the Image.Save() function (you can also save the image in other image formats such as JPG and BMP).
Code example:
- 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 an Image
const ExcelToImage = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input file into the virtual file system (VFS)
const inputFileName = 'ToImageSample.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);
// Convert the sheet to an image
let image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn);
// Specify the output image file path
const outputFileName = 'SheetToImage.png';
//Save the image
image.Save(outputFileName);
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });
// 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 Image Using JavaScript in React</h1>
<button onClick={ExcelToImage} 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 image:

The below screenshot shows the input Excel worksheet and the converted image:

Convert an Excel Worksheet to an Image without White Margins with JavaScript in React
When converting an Excel worksheet to an image, the default output may include unnecessary white margins that can affect the appearance and usability of the image. If you want to remove these white margins, you can set the left, right, top, and bottom margins of the worksheet to zero. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Remove all margins from the worksheet by setting its left, right, top, and bottom margin values to zero using the Worksheet.PageSetup.TopMargin, Worksheet.PageSetup.BottomMargin, Worksheet.PageSetup.LeftMargin, and Worksheet.PageSetup.RightMargin properties.
- Convert the worksheet to an image using the Worksheet.ToImage() function.
- Save the image to a PNG file using the Image.Save() function.
Code example:
- 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 an Image
const ExcelToImage = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input file into the virtual file system (VFS)
const inputFileName = 'ToImageSample.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);
// Set all margins of the worksheet to zero
sheet.PageSetup.LeftMargin = 0;
sheet.PageSetup.BottomMargin = 0;
sheet.PageSetup.TopMargin = 0;
sheet.PageSetup.RightMargin = 0;
// Convert the sheet to image
let image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn);
// Specify the output image file path
const outputFileName = 'SheetToImageWithoutMargins.png';
//Save the image
image.Save(outputFileName);
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });
// 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 Image Using JavaScript in React</h1>
<button onClick={ExcelToImage} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Convert a Specific Cell Range to an Image with JavaScript in React
Converting a specific cell range to an image lets you highlight essential data, making it easy to share or embed without including unnecessary information. Spire.XLS for JavaScript enables you to convert a specific cell range from a worksheet into an image by providing the starting and ending row and column indices as parameters to the Worksheet.ToImage() function. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Convert a specific cell range of the worksheet to an image using the Worksheet.ToImage() function and pass the index of the start row, start column, end row, and end column of the cell range to the method as parameters.
- Save the image to a PNG file using the Image.Save() function
Code example:
- 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 Cell Range to Image
const ExcelToImage = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input file into the virtual file system (VFS)
const inputFileName = 'ToImageSample.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);
// Convert a specific cell range of the worksheet to image
let image = sheet.ToImage(5, 2, 17, 5);
// Specify the output image file path
const outputFileName = 'CellRangeToImage.png';
//Save the image
image.Save(outputFileName);
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });
// 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 a Cell Range to Image Using JavaScript in React</h1>
<button onClick={ExcelToImage} 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.
Microsoft Excel is a powerful tool for managing and analyzing data, but its file format can be difficult to share, especially when recipients don’t have Excel. Converting an Excel file to PDF solves this problem by preserving the document’s layout, fonts, and formatting, ensuring it looks the same on any device. PDFs are universally accessible, making them ideal for sharing reports, invoices, or presentations. They also prevent unwanted editing, ensuring the content remains intact and easily viewable by anyone. In this article, we will demonstrate how to convert Excel to PDF in React using Spire.XLS for JavaScript.
- Convert an Entire Excel Workbook to PDF
- Convert a Specific Worksheet to PDF
- Fit Sheet on One Page while Converting a Worksheet to PDF
- Customize Page Margins while Converting a Worksheet to PDF
- Specify Page Size while Converting a Worksheet to PDF
- Convert a Cell Range to PDF
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. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project
Convert an Entire Excel Workbook to PDF
Converting an entire Excel workbook to PDF allows users to share all sheets in a single, universally accessible file. Using the Workbook.SaveToFile() function of Spire.XLS for JavaScript, you can easily save the entire workbook in PDF format. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- Create a Workbook object using the wasmModule.Workbook.Create() function.
- Load the Excel file using the Workbook.LoadFromFile() function.
- Save the Excel file to PDF using the Workbook.SaveToFile() function.
Code example:
- 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 Excel file to PDF
const ExcelToPDF = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input file into the virtual file system (VFS)
const inputFileName = 'Sample.xlsx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Specify the output PDF file path
const outputFileName = 'ToPDF.pdf';
// Create a new workbook
const workbook = wasmModule.Workbook.Create();
// Load an existing Excel document
workbook.LoadFromFile({fileName: inputFileName});
//Save to PDF
workbook.SaveToFile({fileName: outputFileName , fileFormat: wasmModule.FileFormat.PDF});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 File to PDF Using JavaScript in React</h1>
<button onClick={ExcelToPDF} 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 download the PDF version of the Excel file:

Below is the converted PDF document:

Convert a Specific Worksheet to PDF
To convert a single worksheet to PDF, use the Worksheet.SaveToPdf() function in Spire.XLS for JavaScript. This feature lets you efficiently extract and convert only the necessary worksheet, making your reporting process more streamlined. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Save the worksheet to PDF using the Worksheet.SaveToPdf() function.
Code example:
- 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 Excel file to PDF
const ExcelToPDF = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// 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 second worksheet
let sheet = workbook.Worksheets.get(1);
// Specify the output PDF file path
const outputFileName = sheet.Name + '.pdf';
//Save the worksheet to PDF
sheet.SaveToPdf({fileName: outputFileName});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={ExcelToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Fit Sheet on One Page while Converting a Worksheet to PDF
Fitting a worksheet onto a single page in the output PDF enhances readability, especially for large datasets. Spire.XLS for JavaScript offers the Workbook.ConverterSetting.SheetFitToPage property, which determines whether the worksheet content should be scaled to fit on a single page when saved as a PDF. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- Create a Workbook object using the wasmModule.Workbook.Create() function.
- Load the Excel file using the Workbook.LoadFromFile() function.
- Fit the worksheet on one page by setting the Workbook.ConverterSetting.SheetFitToPage property to true.
- Get a specific worksheet using the Workbook.Worksheets.get(index) function.
- Save the worksheet to PDF using the Worksheet.SaveToPdf() function.
Code example:
- 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 Excel file to PDF
const ExcelToPDF = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// 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});
// Fit sheet on one page
workbook.ConverterSetting.SheetFitToPage = true;
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Specify the output PDF file path
const outputFileName = 'FitSheetOnOnePage.pdf';
//Save the worksheet to PDF
sheet.SaveToPdf({fileName: outputFileName});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={ExcelToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Customize Page Margins while Converting a Worksheet to PDF
Customizing page margins when converting an Excel worksheet to PDF ensures that your content is well-aligned and visually appealing. Using the Worksheet.PageSetup.TopMargin, Worksheet.PageSetup.BottomMargin, Worksheet.PageSetup.LeftMargin, and Worksheet.PageSetup.RightMargin properties, you can adjust or remove page margins as needed. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Adjust the page margins of the worksheet using the Worksheet.PageSetup.PageMargins property.
- Save the worksheet to PDF using the Worksheet.SaveToPdf() function.
Code example:
- 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 Excel file to PDF
const ExcelToPDF = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// 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);
// Adjust page margins of the worksheet
sheet.PageSetup.TopMargin = 0.5;
sheet.PageSetup.BottomMargin = 0.5;
sheet.PageSetup.LeftMargin = 0.3;
sheet.PageSetup.RightMargin = 0.3;
// Specify the output PDF file path
const outputFileName = 'ToPdfWithSpecificPageMargins.pdf';
//Save the worksheet to PDF
sheet.SaveToPdf({fileName: outputFileName});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={ExcelToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Specify Page Size while Converting a Worksheet to PDF
Choosing the correct page size when converting an Excel worksheet to PDF is essential for meeting specific printing or submission standards. Spire.XLS for JavaScript offers the Worksheet.PageSetup.PaperSize property, which allows you to select from various predefined page sizes or set a custom size. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Set the page size of the worksheet using the Worksheet.PageSetup.PaperSize property.
- Save the worksheet to PDF using the Worksheet.SaveToPdf() function.
Code example:
- 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 Excel file to PDF
const ExcelToPDF = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// 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);
// Set the page size of the worksheet
sheet.PageSetup.PaperSize = wasmModule.PaperSizeType.PaperA3;
// Specify the output PDF file path
const outputFileName = 'ToPdfWithSpecificPageSize.pdf';
//Save the worksheet to PDF
sheet.SaveToPdf({fileName: outputFileName});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={ExcelToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Convert a Cell Range to PDF
Converting a specific cell range to PDF allows users to export only a selected portion of the worksheet, ideal for focused reporting or sharing key data points. Using the Worksheet.PageSetup.PrintArea property, you can specify a cell range for conversion. The key steps are as follows.
- Load the font file to ensure correct text rendering.
- 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.
- Specify the cell range of the worksheet for conversion using the Worksheet.PageSetup.PrintArea property.
- Save the worksheet to PDF using the Worksheet.SaveToPdf() function.
Code example:
- 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 Excel file to PDF
const ExcelToPDF = async () => {
if (wasmModule) {
// Load the ARIALUNI.TTF font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// 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);
// Set the page size of the worksheet
sheet.PageSetup.PrintArea = "B5:E17";
// Specify the output PDF file path
const outputFileName = 'CellRangeToPDF.pdf';
//Save the worksheet to PDF
sheet.SaveToPdf({fileName: outputFileName});
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 a Cell Range to PDF Using JavaScript in React</h1>
<button onClick={ExcelToPDF} 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.