Lock Cells, Rows, and Columns in Excel with JavaScript in React
When working with Excel, you may sometimes need to protect critical data while allowing users to edit other parts of the worksheet. This is especially important for scenarios where certain formulas, headers, or reference values must remain unchanged to ensure data integrity. By locking specific areas, you can prevent accidental modifications, maintain consistency, and control access to key information within the spreadsheet. In this article, you will learn how to lock cells, rows, and columns in Excel in React using JavaScript and the Spire.XLS for JavaScript library.
Install Spire.XLS for JavaScript
To get started with locking cells, rows, and columns in Excel files within 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. 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
Lock Cells in Excel
Spire.XLS for JavaScript offers the Worksheet.Range.get().Style.Locked property, allowing you to protect critical data cells while enabling edits to the rest of the worksheet. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load a sample Excel file using the Workbook.LoadFromFile() method.
- Get the first worksheet using the Workbook.Worksheets.get() method.
- Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
- Set text for specific cells using the Worksheet.Range.get().Text property and then lock them by setting the Worksheet.Range.get().Style.Locked property to "true".
- Protect the worksheet with a password using the Worksheet.Protect() method.
- Save the result file 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 lock specific cells in Excel const LockExcelCells = 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 Excel 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 the Excel file from the virtual file system workbook.LoadFromFile({fileName: inputFileName}); // Get the first worksheet let sheet = workbook.Worksheets.get(0); // Unlock all cells in the used range of the worksheet sheet.Range.Style.Locked = false; // Lock a specific cell in the worksheet sheet.Range.get("A1").Text = "Locked"; sheet.Range.get("A1").Style.Locked = true; // Lock a specific cell range in the worksheet sheet.Range.get("C1:E3").Text = "Locked"; sheet.Range.get("C1:E3").Style.Locked = true; // Protect the worksheet with a password sheet.Protect({password: "123", options: wasmModule.SheetProtectionType.All}); let outputFileName = "LockCells.xlsx"; // Save the resulting 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 workbooks workbook.Dispose(); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Lock Specific Cells in Excel Using JavaScript in React</h1> <button onClick={LockExcelCells} disabled={!wasmModule}> Lock </button> </div> ); } export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Lock" button to lock specific cells in the Excel file:
Upon opening the output Excel sheet and attempting to edit the protected cells, a dialog box will appear, notifying you that the cell you're trying to change is on a protected sheet:
Lock Rows in Excel
If you need to preserve row-based data, such as headers or summaries, you can lock entire rows using the Worksheet.Rows.get().Style.Locked property in Spire.XLS for JavaScript. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load a sample Excel file using the Workbook.LoadFromFile() method.
- Get the first worksheet using the Workbook.Worksheets.get() method.
- Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
- Set text for a specific row using the Worksheet.Rows.get().Text property and then lock it by setting the Worksheet.Rows.get().Style.Locked property to "true".
- Protect the worksheet with a password using the Worksheet.Protect() method.
- Save the result file 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 lock specific rows in Excel const LockExcelRows = 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 Excel 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 the Excel file from the virtual file system workbook.LoadFromFile({fileName: inputFileName}); // Get the first worksheet let sheet = workbook.Worksheets.get(0); // Unlock all cells in the used range of the worksheet sheet.Range.Style.Locked = false; // Lock the third row in the worksheet sheet.Rows.get(2).Text = "Locked"; sheet.Rows.get(2).Style.Locked = true; // Protect the worksheet with a password sheet.Protect({password: "123", options: wasmModule.SheetProtectionType.All}); let outputFileName = "LockRows.xlsx"; // Save the resulting 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 workbooks workbook.Dispose(); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Lock Specific Rows in Excel Using JavaScript in React</h1> <button onClick={LockExcelRows} disabled={!wasmModule}> Lock </button> </div> ); } export default App;
Lock Columns in Excel
To maintain the integrity of key vertical data, such as fixed identifiers or category labels, you can lock entire columns using the Worksheet.Columns.get().Style.Locked property in Spire.XLS for JavaScript. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load a sample Excel file using the Workbook.LoadFromFile() method.
- Get the first worksheet using the Workbook.Worksheets.get() method.
- Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
- Set text for a specific column using the Worksheet.Columns.get().Text property and then lock it by setting the Worksheet.Columns.get().Style.Locked property to "true".
- Protect the worksheet with a password using the Worksheet.Protect() method.
- Save the result file 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 lock specific columns in Excel const LockExcelColumns = 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 Excel 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 the Excel file from the virtual file system workbook.LoadFromFile({fileName: inputFileName}); // Get the first worksheet let sheet = workbook.Worksheets.get(0); // Unlock all cells in the used range of the worksheet sheet.Range.Style.Locked = false; // Lock the fourth column in the worksheet sheet.Columns.get(3).Text = "Locked"; sheet.Columns.get(3).Style.Locked = true; // Protect the worksheet with a password sheet.Protect({password: "123", options: wasmModule.SheetProtectionType.All}); let outputFileName = "LockColumns.xlsx"; // Save the resulting 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 workbooks workbook.Dispose(); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Lock Specific Columns in Excel Using JavaScript in React</h1> <button onClick={LockExcelColumns} disabled={!wasmModule}> Lock </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.
Protect or Unprotect Excel Workbooks with JavaScript in React
As businesses increasingly rely on web-based platforms for data manipulation and sharing, the ability to programmatically protect or unprotect Excel files becomes crucial. These security settings not only ensure sensitive information is shielded from unauthorized access but also facilitate seamless collaboration among team members by allowing controlled access to specific data sets. By leveraging JavaScript in React, developers can implement these features natively, providing a robust solution to manage data confidentiality and integrity directly within their applications. In this article, we will explore how to use Spire.XLS for JavaScript to protect and unprotect Excel workbooks using JavaScript in React applications.
- Password-Protect an Excel Workbook using JavaScript
- Protect an Excel Worksheet with Specific Permissions
- Set Editable Ranges when Protect an Excel Worksheet
- Unprotect an Excel Worksheet with JavaScript
- Reset or Remove the Password of an Encrypted Excel Workbook
Install Spire.XLS for JavaScript
To get started with protecting and unprotecting Excel 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
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
Password-Protect an Excel Workbook using JavaScript
Spire.XLS for JavaScript offers the Workbook.Protect(filename: string) method to encrypt an Excel file with a password. This functionality allows developers to secure the entire Excel workbook. Below are the steps to implement this:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Load the Excel file to the virtual file system using the wasmModule.FetchFileToVFS() method
- Create an instance of the Workbook class using the wasmModule.Workbook.Create() method.
- Load the Excel file to the Workbook instance using the Workbook.LoadFromFile() method.
- Protect the workbook with a password using the Workbook.Protect() method.
- Save the workbook to a file using Workbook.SaveToFile() method.
- Create a download link for the result file.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the 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 protect an Excel workbook with a password const EncryptExcel = async () => { if (wasmModule) { // Specify the input and output file names const inputFileName = 'Sample.xlsx'; const outputFileName = 'EncryptedWorkbook.xlsx'; // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create an instance of the Workbook class const workbook = wasmModule.Workbook.Create(); // Load the Excel workbook from the input file workbook.LoadFromFile({ fileName: inputFileName }); // Encrypt the workbook with a password workbook.Protect('password') // Save the workbook workbook.SaveToFile({ fileName: outputFileName }); // Read the workbook from the VFS const excelArray = await wasmModule.FS.readFile(outputFileName); // Generate a Blob from the result Excel file array and trigger a download const blob = new Blob([excelArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${outputFileName}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Protect Excel Workbook Using JavaScript in React</h1> <button onClick={EncryptExcel} disabled={!wasmModule}> Encrypt and Download </button> </div> ); } export default App;
Protect an Excel Worksheet with Specific Permissions
Spire.XLS for JavaScript enables developers to secure worksheets with specific permissions using the Worksheet.Protect() method, such as restricting edits while allowing formatting or filtering, or simply restricting all changes. The permissions are specified by the SheetProtectionType Enum class.
Protection Type | Allow users to |
Content | Modify or insert content. |
DeletingColumns | Delete columns. |
DeletingRows | Delete rows. |
Filtering | Set filters. |
FormattingCells | Format cells. |
FormattingColumns | Format columns. |
FormattingRows | Format rows. |
InsertingColumns | Insert columns. |
InsertingRows | Insert rows. |
InsertingHyperlinks | Insert hyperlinks. |
LockedCells | Select locked cells. |
UnlockedCells | Select unlocked cells. |
Objects | Modify drawing objects. |
Scenarios | Modify saved scenarios. |
Sorting | Sort data. |
UsingPivotTables | Use the pivot table and pivot chart. |
All | Do any operations listed above on the protected worksheet. |
None | Do nothing on the protected worksheet. |
Follow these steps to protect a worksheet with specific permissions:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Load the Excel file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Workbook instance with the wasmModule.Workbook.Create() method.
- Load the Excel file into the Workbook using the Workbook.LoadFromFile() method.
- Retrieve the desired worksheet using the Workbook.Worksheets.get(index) method.
- Protect the worksheet and allow only filtering with the Worksheet.Protect(password, SheetProtectionType.None) method.
- Save the workbook using the Workbook.SaveToFile() method.
- Create a download link for the protected file.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the 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 protect an Excel worksheet with a password const EncryptExcelWorksheet = async () => { if (wasmModule) { // Specify the input and output file names const inputFileName = 'Sample.xlsx'; const outputFileName = 'ProtectedWorksheet.xlsx'; // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create an instance of the Workbook class const workbook = wasmModule.Workbook.Create(); // Load the Excel workbook from the input file workbook.LoadFromFile({ fileName: inputFileName }); // Get a worksheet const sheet = workbook.Worksheets.get(0); // Protect the worksheet with a specific permission sheet.Protect({ password: '123456', options: wasmModule.SheetProtectionType.None}); // Save the workbook workbook.SaveToFile({ fileName: outputFileName }); // Read the workbook from the VFS const excelArray = await wasmModule.FS.readFile(outputFileName); // Generate a Blob from the result Excel file array and trigger a download const blob = new Blob([excelArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${outputFileName}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Protect Excel Worksheet Using JavaScript in React</h1> <button onClick={EncryptExcelWorksheet} disabled={!wasmModule}> Encrypt and Download </button> </div> ); } export default App;
Set Editable Ranges when Protect an Excel Worksheet
If certain cell ranges need to remain editable while protecting other areas, developers can use the Worksheet.AddAllowEditRange(name: string, range: CellRange) method to define editable ranges, and then protect the worksheet with specific permissions using the Worksheet.Protect({password: string, options: wasmModule.SheetProtectionType.All}) method.
The steps are as follows:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Load the Excel file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Workbook instance with the wasmModule.Workbook.Create() method.
- Load the Excel file into the Workbook using the Workbook.LoadFromFile() method.
- Obtain the desired worksheet using the Workbook.Worksheets.get(index) method.
- Get the cell ranges to allow editing using the Worksheet.Range.get() method.
- Add the cell ranges to editable ranges using the Worksheet.AddAllowEditRange() method.
- Protect the worksheet with the Worksheet.Protect({password: string, options: wasmModule.SheetProtectionType.All}) method.
- Save the workbook using the Workbook.SaveToFile() method.
- Create a download link for the protected file.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the 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 protect an Excel worksheet and add editable ranges const EncryptExcelWorksheetWithEditableRange = async () => { if (wasmModule) { // Specify the input and output file names const inputFileName = 'Sample.xlsx'; const outputFileName = 'EditableRanges.xlsx'; // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create an instance of the Workbook class const workbook = wasmModule.Workbook.Create(); // Load the Excel workbook from the input file workbook.LoadFromFile({ fileName: inputFileName }); // Get a worksheet const sheet = workbook.Worksheets.get(0); // Add editable ranges const range1 = sheet.Range.get('A8:A10'); sheet.AddAllowEditRange({ title: "Editable Range 1", range: range1 }); const range2 = sheet.Range.get('A13:G18'); sheet.AddAllowEditRange({ title: "Editable Range 2", range: range2 }); // Protect the worksheet sheet.Protect({ password: '123456', options: wasmModule.SheetProtectionType.All}); // Save the workbook workbook.SaveToFile({ fileName: outputFileName }); // Read the workbook from the VFS const excelArray = await wasmModule.FS.readFile(outputFileName); // Generate a Blob from the result Excel file array and trigger a download const blob = new Blob([excelArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${outputFileName}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Protect Excel Worksheet with Editable Ranges Using JavaScript in React</h1> <button onClick={EncryptExcelWorksheetWithEditableRange} disabled={!wasmModule}> Encrypt and Download </button> </div> ); } export default App;
Unprotect an Excel Worksheet with JavaScript
Developers can easily remove the password and unprotect an Excel worksheet by invoking the Worksheet.Unprotect(password: string) method, granting access and edit permissions to all users. The detailed steps are as follows:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Load the Excel file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Workbook instance with the wasmModule.Workbook.Create() method.
- Load the Excel file into the Workbook using the Workbook.LoadFromFile() method.
- Get the worksheet to unprotect using the Workbook.Worksheets.get() method.
- Remove the password protection using the Worksheet.Unprotect() method.
- Save the workbook using the Workbook.SaveToFile() method.
- Create a download link for the protected file.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the 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 unprotect an Excel worksheet const UnprotectExcelWorksheet = async () => { if (wasmModule) { // Specify the input and output file names const inputFileName = 'ProtectedWorksheet.xlsx'; const outputFileName = 'UnprotectedWorksheet.xlsx'; // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create an instance of the Workbook class const workbook = wasmModule.Workbook.Create(); // Load the Excel workbook from the input file workbook.LoadFromFile({ fileName: inputFileName }); // Get the worksheet to unprotect const sheet = workbook.Worksheets.get(0); // Remove the password protection sheet.Unprotect('password'); // Save the workbook workbook.SaveToFile({ fileName: outputFileName }); // Read the workbook from the VFS const excelArray = await wasmModule.FS.readFile(outputFileName); // Generate a Blob from the result Excel file array and trigger a download const blob = new Blob([excelArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${outputFileName}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Unprotect Excel Worksheet Using JavaScript in React</h1> <button onClick={UnprotectExcelWorksheet} disabled={!wasmModule}> Unprotect and Download </button> </div> ); } export default App;
Reset or Remove the Password of an Encrypted Excel Workbook
Spire.XLS for JavaScript provides the Workbook.OpenPassword property to specify the password for encrypted Excel workbooks, allowing developers to load and process them. After loading the encrypted workbook, developers can use the Workbook.Unprotect(password: string) method to remove the password or the Workbook.Protect(newPassword: string) method to set a new one. The steps are as follows:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Load the Excel file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Workbook instance with the wasmModule.Workbook.Create() method.
- Specify the password through the Workbook.OpenPassword property.
- Load the encrypted Excel file into the Workbook using the Workbook.LoadFromFile() method.
- Unprotect the workbook using the Workbook.Unprotect(password: string) method or set a new password using the Workbook.Protect(newPassword: string) method.
- Save the workbook using the Workbook.SaveToFile() method.
- Create a download link for the protected file.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the 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 unprotect an Excel workbook const RemoveResetExcelPassword = async () => { if (wasmModule) { // Specify the input and output file names const inputFileName = 'EncryptedWorkbook.xlsx'; const outputFileName = 'DecryptedWorkbook.xlsx'; // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create an instance of the Workbook class const workbook = wasmModule.Workbook.Create(); // Specify the password of the workbook workbook.OpenPassword = 'password'; // Load the Excel workbook from the input file workbook.LoadFromFile({ fileName: inputFileName }); // Decrypt the workbook workbook.UnProtect('password') // Reset the password // workbook.Protect("NewPassword") // Save the workbook workbook.SaveToFile({ fileName: outputFileName }); // Read the workbook from the VFS const excelArray = await wasmModule.FS.readFile(outputFileName); // Generate a Blob from the result Excel file array and trigger a download const blob = new Blob([excelArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${outputFileName}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Remove the Password of Excel Workbook Using JavaScript in React</h1> <button onClick={RemoveResetExcelPassword} disabled={!wasmModule}> Decrypt and Download </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.