Knowledgebase (2300)
HTML, the backbone of web development, is widely used to build and present content on the web. While HTML is great for creating dynamic and interactive web pages, it is not well suited for creating professional-looking documents. When faced with such requirements, converting HTML to Word format is an ideal solution.
By implementing the Html to Word conversion, you can preserve the structure and content of the HTML while applying appropriate formatting and styles in Word to ensure the document look more professional. In this article, you will learn how to convert HTML to Word in React using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started with converting Word documents to PDF in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
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.Doc for JavaScript in a React Project
Convert an HTML File to Word with JavaScript in React
With Spire.Doc for JavaScript, you can simply load an HTML file and then save it as a Word Doc or Docx format through the Document.SaveToFile() function. The following are the main steps to convert an HTML file to Word in JavaScript.
- Load the font file to ensure correct text rendering.
- Create a new document using the wasmModule.Document.Create() function.
- Load the HTML file using the Document.LoadFromFile() function.
- Save the HTML file to a Word file using the Document.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 spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} 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.Doc.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 HTML file to Word
const HtmlToWord = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('CALIBRI.ttf','/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Specify the input and output file paths
const inputFileName = 'sample1.html';
const outputFileName = 'HtmlToWord.docx';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName,'', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the HTML file
doc.LoadFromFile({fileName: inputFileName,fileFormat: wasmModule.FileFormat.Html,validationType: wasmModule.XHTMLValidationType.None});
// Save the HTML file to a Word file
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx});
// Read the generated Word file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the Word file
const modifiedFile = new Blob([modifiedFileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
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
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert HTML File to Word Using JavaScript in React</h1>
<button onClick={HtmlToWord} 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 Word file generated from an HTML file:

Below is the input HTML file and the converted Word file:

Convert an HTML String to Word with JavaScript in React
You can also convert an HTML string to Word by calling the Paragraph.AppendHTML() function to add the HTML string to a paragraph in Word and then save the Word document. The following are the main steps to convert an HTML string to a Word file in JavaScript.
- Load the font file to ensure correct text rendering.
- Specify the HTML string
- Create a new document using the wasmModule.Document.Create() function.
- Add a new section using the Document.AddSection() function.
- Add a paragraph to the section using the Section.AddParagraph() function.
- Append the HTML string to the paragraph using the Paragraph.AppendHTML() function.
- Save the Word document using the Document.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 spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} 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.Doc.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 HTML string to Word
const HtmlStringToWord = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('CALIBRI.ttf','/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Specify the output file path
const outputFileName = 'HtmlStringToWord.docx';
// Specify the HTML string
let HTML = "<html><head><title>HTML to Word Example</title><style>, body {font-family: 'Calibri';}, h1 {color: #FF5733; font-size: 24px; margin-bottom: 20px;}, p {color: #333333; font-size: 16px; margin-bottom: 10px;}";
HTML+="ul {list-style-type: disc; margin-left: 20px; margin-bottom: 15px;}, li {font-size: 14px; margin-bottom: 5px;}, table {border-collapse: collapse; width: 100%; margin-bottom: 20px;}";
HTML+= "th, td {border: 1px solid #CCCCCC; padding: 8px; text-align: left;}, th {background-color: #F2F2F2; font-weight: bold;}, td {color: #0000FF;}</style></head>";
HTML+="<body><h1>This is a Heading</h1><p>This is a paragraph demonstrating the conversion of HTML to Word document.</p><p>Here's an example of an unordered list:</p><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>";
HTML+="<p>Here's a table:</p><table><tr><th>Product</th><th>Quantity</th><th>Price</th></tr><tr><td>Jacket</td><td>30</td><td>$150</td></tr><tr><td>Sweater</td><td>25</td><td>$99</td></tr></table></body></html>";
// Create a new document
const doc = wasmModule.Document.Create();
// Add a section to the document
let section = doc.AddSection();
// Add a paragraph to the section
let paragraph = section.AddParagraph();
// Append the HTML string to the paragraph
paragraph.AppendHTML(HTML.toString('utf8',0,HTML.length));
// Save the Word file
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2016});
// Read the generated Word file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the Word file
const modifiedFile = new Blob([modifiedFileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
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
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert HTML String to Word Using JavaScript in React</h1>
<button onClick={HtmlStringToWord} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Doc 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.