Knowledgebase (2407)
Children categories
Hide, Unhide, and Control the Conversion of Excel Worksheets with JavaScript in React
2026-08-18 06:41:57 Written by Lisa LiIn daily work, we often need to hide some worksheets to simplify the interface display or protect sensitive data, and we can unhide them when necessary. In addition, when converting a workbook to HTML, you may also need to control whether hidden worksheets appear in the conversion result. Spire.XLS for JavaScript performs these operations directly in the browser based on WebAssembly, managing input and output files through the virtual file system (VFS), without any backend service support.
This article covers three core feature points:
- Hide a Worksheet
- Show a Hidden Worksheet
- Control Whether to Include Hidden Worksheets When Converting to HTML
For installation and project configuration, please refer to How to Integrate Spire.XLS for JavaScript in a React Project. The following examples assume that Spire.XLS is installed and the WebAssembly module has been initialized.
Hide a Worksheet
Hiding a worksheet is often used to simplify the display of a workbook or protect internal data. With Spire.XLS for JavaScript, you can hide a specified worksheet by setting the Visibility property of the worksheet object to WorksheetVisibility.Hidden.
function App() {
const hideSheet = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and Excel file into VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'HideOrShowWorksheet.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// Get the worksheet named "Sheet1" and hide it
let sheet1 = workbook.Worksheets.get("Sheet1");
sheet1.Visibility = xlsModule.WorksheetVisibility.Hidden;
// Save the workbook
const outputFileName = "HideWorksheet_output.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to release resources
workbook.Dispose();
// Read the converted file from VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Hide Worksheet</h1>
<button onClick={hideSheet}>
Start
</button>
</div>
);
}
export default App;
Original document (Sheet2 is already hidden)
Hide Sheet1 
Show a Hidden Worksheet
When you need to view or edit a hidden worksheet again, you can show it again by setting the Visibility property to WorksheetVisibility.Visible.
function App() {
const showSheet = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and Excel file into VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'HideOrShowWorksheet.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// Get the second worksheet and set it as visible
let sheet2 = workbook.Worksheets.get(1);
sheet2.Visibility = xlsModule.WorksheetVisibility.Visible;
// Save the workbook
const outputFileName = "ShowWorksheet_output.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to release resources
workbook.Dispose();
// Read the converted file from VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Show Worksheet</h1>
<button onClick={showSheet}>
Start
</button>
</div>
);
}
export default App;
Unhide Sheet2 
Control Whether to Include Hidden Worksheets When Converting to HTML
When converting to HTML, you can use the skipHideSheet parameter of the SaveToHtml method to control whether hidden worksheets are included in the conversion result. When set to false, the generated HTML includes hidden worksheets; when set to true, hidden worksheets are skipped and only visible worksheets remain in the HTML.
function App() {
const saveToHtml = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and Excel file into VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'HideOrShowWorksheet.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// Hide the worksheet named "Sheet1"
let sheet1 = workbook.Worksheets.get("Sheet1");
sheet1.Visibility = xlsModule.WorksheetVisibility.Hidden;
// Set the output HTML file name
const result = "result.html";
// false --- Save HTML with hidden worksheets
// true --- Save HTML without hidden worksheets
workbook.SaveToHtml({
fileName: result,
skipHideSheet: false
});
// Dispose of the workbook object to release resources
workbook.Dispose();
// Read the converted file from VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(result);
const blob = new Blob([fileArray], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = result;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Workbook to HTML</h1>
<button onClick={saveToHtml}>
Start
</button>
</div>
);
}
export default App;
After conversion 
FAQ
The HTML conversion result contains extra worksheets
Cause: The original Excel document has multiple hidden worksheets. When the skipHideSheet parameter of SaveToHtml is set to false, all hidden worksheets appear in the conversion result.
Solution: You can use the following code to iterate through and check the hidden state of all sheets in the Excel file.
const sheetCount = workbook.Worksheets.Count;
for (let i = 0; i < sheetCount; i++) {
let sheet = workbook.Worksheets.get(i);
const visibility = sheet.Visibility;
}
Get a Free License
If you want to remove the evaluation message in the generated documents or get rid of functional limitations, please contact us to get a temporary license valid for 30 days.
Combining PDF files is a common requirement in document management applications. For example, a React application may need to assemble invoices, reports, contracts, or scanned pages into a single PDF before the file is archived or shared. When the source documents do not need to be uploaded to a server, performing the operation in the browser can also simplify the workflow.
In this tutorial, you will learn how to merge PDF documents in a React application using Spire.PDF for JavaScript. The first example combines several complete PDF files in one operation. The second example provides more precise control by taking selected pages from different PDFs and adding them to a new document.
On this page:
- Install Spire.PDF for JavaScript in a React Project
- Merge Multiple PDF Documents in React
- Merge Selected Pages from Different PDF Documents in React
- Important Implementation Notes
- Conclusion
Install Spire.PDF for JavaScript in a React Project
Open a terminal in the root directory of your React project and install the spire.office package:
npm i spire.office
After the installation is complete, copy the following runtime files and folder from the installed package to the React project's public folder:
public/
├── _framework/
├── spire.pdf.js
├── Spire.Pdf.Wasm.zip
├── spire.common.js
└── Spire.Common.Wasm.zip
The JavaScript loader, WebAssembly resources, and supporting framework files must remain accessible as static assets when the application runs. For detailed setup instructions and the exact integration process, see How to Integrate Spire.PDF for JavaScript in a React Project.
For the examples in this article, also place the input PDF files in the public folder so that the application can retrieve them with fetch():
public/
├── input_1.pdf
├── input_2.pdf
├── input_3.pdf
└── ...
Merge Multiple PDF Documents in React
If every page in every source file should appear in the result, the most direct approach is to use the PdfMerger.Merge() method. It accepts an array of input file paths, merges the files in the order in which they appear in the array, and writes the result to the WebAssembly virtual file system.
The following React component merges input_1.pdf, input_2.pdf, and input_3.pdf into a single document named MergedPdf.pdf:
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
const [isGenerating, setIsGenerating] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.pdf.js:', error);
}
})();
}, []);
const loadPdfToVfs = async (fileName) => {
const publicUrl = process.env.PUBLIC_URL || '';
const response = await fetch(`${publicUrl}/${fileName}`);
if (!response.ok) {
throw new Error(`Failed to load ${fileName}: ${response.status} ${response.statusText}`);
}
const fileBytes = new Uint8Array(await response.arrayBuffer());
const pdfHeader = String.fromCharCode(...fileBytes.slice(0, 4));
if (pdfHeader !== '%PDF') {
throw new Error(`${fileName} was loaded, but it is not a valid PDF file.`);
}
window.dotnetRuntime.Module.FS.writeFile(fileName, fileBytes, { flags: 'w+' });
return fileName;
};
const MergePdfs = async () => {
const wasmModule = window.wasmModule?.spirepdf;
if (!wasmModule || isGenerating) {
return;
}
setIsGenerating(true);
setErrorMessage('');
try {
const inputFiles = await Promise.all([
loadPdfToVfs('input_1.pdf'),
loadPdfToVfs('input_2.pdf'),
loadPdfToVfs('input_3.pdf'),
]);
const outputFileName = 'MergedPdf.pdf';
const mergeOp = new wasmModule.MergerOptions();
wasmModule.PdfMerger.Merge({
inputFiles,
outputFile: outputFileName,
pdfMergeOptions: mergeOp
});
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
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);
} catch (error) {
console.error('Failed to merge PDFs:', error);
setErrorMessage(error.message || 'Failed to merge PDFs.');
} finally {
setIsGenerating(false);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Merge PDF Documents in React</h1>
<button onClick={MergePdfs} disabled={!wasmModule || isGenerating}>
{isGenerating ? 'Generating...' : 'Generate'}
</button>
{errorMessage && <p style={{ color: 'crimson' }}>{errorMessage}</p>}
</div>
);
}
export default App;
Output:

How the Code Works
The component first loads spire.pdf.js inside useEffect(). Because the module is initialized asynchronously, the Generate button remains disabled until the runtime is ready.
The loadPdfToVfs() function then performs three tasks for each source document:
- It retrieves the PDF from the
publicdirectory withfetch(). - It checks the first four bytes for the
%PDFsignature to help catch missing files or non-PDF responses. - It writes the file bytes to the WebAssembly virtual file system, where Spire.PDF can access them.
After all three files have been loaded, PdfMerger.Merge() combines them in the order specified by inputFiles. The output is read from the virtual file system, converted to a PDF Blob, and downloaded through a temporary object URL.
To change the merge order, simply rearrange the entries in the array. For example, the following order would place input_3.pdf first:
const inputFiles = await Promise.all([
loadPdfToVfs('input_3.pdf'),
loadPdfToVfs('input_1.pdf'),
loadPdfToVfs('input_2.pdf'),
]);
Merge Selected Pages from Different PDF Documents in React
Merging complete documents is not always necessary. You may instead need to create a new PDF from a cover page in one file and a page range in another file. In this situation, load the source files as PdfDocument objects and use InsertPage() and InsertPageRange() to construct the output document.
The following example takes the first page from input_1.pdf, appends every page from input_2.pdf, and saves the selected content as MergedPdf.pdf:
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
const [isGenerating, setIsGenerating] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.pdf.js:', error);
}
})();
}, []);
const loadPdfToVfs = async (fileName) => {
const publicUrl = process.env.PUBLIC_URL || '';
const response = await fetch(`${publicUrl}/${fileName}`);
if (!response.ok) {
throw new Error(`Failed to load ${fileName}: ${response.status} ${response.statusText}`);
}
const fileBytes = new Uint8Array(await response.arrayBuffer());
const pdfHeader = String.fromCharCode(...fileBytes.slice(0, 4));
if (pdfHeader !== '%PDF') {
throw new Error(`${fileName} was loaded, but it is not a valid PDF file.`);
}
window.dotnetRuntime.Module.FS.writeFile(fileName, fileBytes, { flags: 'w+' });
return fileName;
};
const MergePdfs = async () => {
const wasmModule = window.wasmModule?.spirepdf;
if (!wasmModule || isGenerating) {
return;
}
setIsGenerating(true);
setErrorMessage('');
try {
const [firstInputFile, secondInputFile] = await Promise.all([
loadPdfToVfs('input_1.pdf'),
loadPdfToVfs('input_2.pdf'),
]);
const outputFileName = 'MergedPdf.pdf';
const firstDocument = new wasmModule.PdfDocument();
const secondDocument = new wasmModule.PdfDocument();
const mergedDocument = new wasmModule.PdfDocument();
firstDocument.LoadFromFile({ fileName: firstInputFile });
secondDocument.LoadFromFile({ fileName: secondInputFile });
if (firstDocument.Pages.Count < 1) {
throw new Error('The first PDF does not contain any pages.');
}
if (secondDocument.Pages.Count < 1) {
throw new Error('The second PDF does not contain any pages.');
}
mergedDocument.InsertPage({ ldDoc: firstDocument, pageIndex: 0 });
mergedDocument.InsertPageRange(secondDocument, 0, secondDocument.Pages.Count - 1);
mergedDocument.SaveToFile({ fileName: outputFileName });
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
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);
} catch (error) {
console.error('Failed to merge PDFs:', error);
setErrorMessage(error.message || 'Failed to merge PDFs.');
} finally {
setIsGenerating(false);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Merge PDF Documents in React</h1>
<button onClick={MergePdfs} disabled={!wasmModule || isGenerating}>
{isGenerating ? 'Generating...' : 'Generate'}
</button>
{errorMessage && <p style={{ color: 'crimson' }}>{errorMessage}</p>}
</div>
);
}
export default App;
Output:

Understanding the Page Selection Logic
The three PdfDocument instances have different roles:
firstDocumentrepresentsinput_1.pdf.secondDocumentrepresentsinput_2.pdf.mergedDocumentis the new PDF that receives the selected pages.
PDF page indexes are zero-based in this example. Therefore, pageIndex: 0 refers to the first page:
mergedDocument.InsertPage({ ldDoc: firstDocument, pageIndex: 0 });
The following statement inserts a continuous range from secondDocument. Its start index is 0, while its end index is secondDocument.Pages.Count - 1, so the complete document is appended:
mergedDocument.InsertPageRange(
secondDocument,
0,
secondDocument.Pages.Count - 1
);
You can change these indexes to merge only the pages required by your application. For instance, this statement inserts pages 2 through 5 from secondDocument because their zero-based indexes are 1 through 4:
mergedDocument.InsertPageRange(secondDocument, 1, 4);
Before using fixed page indexes, make sure the source document contains enough pages. The sample already checks for empty PDFs, but a production application should also validate user-supplied start and end indexes against Pages.Count.
Important Implementation Notes
Keep Runtime and Input Paths Correct
Files stored in the React public directory are requested by URL at runtime. The code uses process.env.PUBLIC_URL so it can construct paths correctly when the application is deployed under a non-root public path. A missing or incorrect file path may return an HTML error page instead of a PDF, which is why the sample verifies the %PDF header before writing the data to the virtual file system.
Wait for WebAssembly Initialization
Spire.PDF cannot process a document until its runtime has finished loading. The wasmModule state controls the button's disabled status, while isGenerating prevents the same operation from being started repeatedly before the current merge has finished.
Validate Page Ranges
When pages are chosen dynamically, check that the start and end indexes are non-negative, that the start index does not exceed the end index, and that both values fall within the source document's page count. This avoids invalid range errors and makes it easier to show a useful message in the React interface.
Release the Download URL
URL.createObjectURL() creates a temporary URL for the generated Blob. Calling URL.revokeObjectURL(url) after the download starts releases that URL and prevents it from remaining in browser memory longer than necessary.
Conclusion
Spire.PDF for JavaScript enables React applications to combine PDF content through a WebAssembly-based workflow. When all pages are required, PdfMerger.Merge() provides a concise way to merge several complete documents in a defined order. When the output must contain only specific content, PdfDocument, InsertPage(), and InsertPageRange() provide page-level control over the result.
With the runtime files configured in the public directory, these techniques can be integrated into document portals, reporting tools, contract workflows, and other React applications that need to assemble PDFs directly in the browser.
In cross-industry data processing scenarios, importing data from CSV and PDF files into Excel is one of the most common and error-prone tasks — finance teams reconcile CSV bank statements, e-commerce teams organize order files exported from multiple platforms, and administrative staff handle PDF statements from suppliers. These files come in all shapes and formats: inconsistent CSV delimiters, fields containing commas, dates appearing in various forms, phone numbers and ID numbers that start with 0 are treated as numbers and lose their leading zeros; PDF tables cannot be edited directly, and copying them into Excel misaligns rows, columns, and merged cells.
The traditional approach is to split columns manually, set formats column by column, and hunt for erroneous cells by eye. A CSV file with a few hundred rows often takes half an hour of repeated adjustment; PDF tables can only be copied and pasted row by row. Traditional methods are also prone to misaligned columns, misplaced dates, and numbers turning into text. As data volume grows, manual processing becomes nearly impossible.
Take a finance team reconciling bank statements, for example: after receiving a CSV, the usual routine is to confirm the encoding in a text editor first, split the columns in Excel, set date and amount formats column by column, and then hunt for anomalous values by eye. A field containing a comma shifts the whole row, accounts starting with 0 lose their leading zeros, and only after repeated adjustment does the table become usable. PDF statements can only be copied and pasted row by row — rows, columns, and merged cells are almost all misaligned, and reconstructing a single statement often eats up half a day.
Comparison with Traditional SDK API Processing
| Traditional Spire.Office for .NET API | Spire.Agent.Office Processing | |
|---|---|---|
| Driving Method | Write code for column splitting, type conversion, and format checking, controlling every step | Describe the goal in natural language; the AI understands and automatically orchestrates the execution path |
| Code Volume | Data import scenarios typically require 500-1000 lines of C# code (including parsers, type conversion, error detection, etc.) | About 10 lines of calling code + one natural language instruction |
| Delimiters & Quoting | Must hand-write parsing logic for edge cases such as commas inside quotes and escape characters | The AI automatically recognizes delimiters and quoted fields and splits columns intelligently |
| Type Detection | Must hard-code date/number/text recognition rules per column; changing rules requires code changes | The AI understands data type semantics and automatically recognizes dates, numbers, and text |
| Error Detection | Must write regex and conditional checks cell by cell; coverage of error types is incomplete | The AI automatically detects anomalies such as type mismatches and column count mismatches and highlights them in red |
| Requirement Changes | Adding a new CSV variant requires modifying code → compiling → deploying | Modify the description in the instruction; takes effect immediately |
This article introduces how to use the Excel AI capabilities of Spire.Agent.Office to implement CSV smart column splitting import and PDF table import, automatically completing data type detection and highlighting erroneous formats in red, with just a single natural language instruction.
For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The following examples assume Spire.Agent.Office is already installed and SpireToken is configured.
CSV Smart Column Splitting Import
CSV is the most common format for data exchange, yet also the least "controllable": the delimiter may be a comma, a tab, or a semicolon; fields may contain commas or line breaks wrapped in quotes; dates, numbers, and text are mixed in the same table; values starting with 0, such as phone numbers and codes, are treated as numbers by default and lose their leading zeros. Import quality directly determines the accuracy of subsequent analysis and reports.
The following example uses the Spire.Agent.Office agent to automatically import a CSV through natural language instructions, completing smart column splitting, data type detection, and highlighting erroneous formats in red:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// CSV source file to be imported (passed as an attachment)
string[] attachmentPaths = new string[] { @"C:\DataImport\employee_sales_data.csv" };
// Save path of the import result document
string savePath = @"C:\DataImport\ToXLSX.xlsx";
// SpireToken Key (apply on the official website)
string key = "sk-TF***************************r";
// Natural language instruction
string instruction = "Process as follows:\n" +
"1. Convert the attached CSV file to an Excel document and apply appropriate formatting to improve readability\n" +
"2. Unify the formats of dates/sales amounts/phone numbers in the file\n" +
"3. Mark erroneous and missing data with a red background";
// AI generation
AIResult result = ImportCsvData(instruction, savePath, key, attachmentPaths);
// AI-assisted CSV import
static AIResult ImportCsvData(string instruction, string savePath, string key, string[] attachmentPaths)
{
// Configure the AI processing options
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Workbook wb = new Workbook())
{
AIDocumentProcessor processor = wb.AI(options);
return processor.ExecuteInstruction(wb, instruction, savePath, attachmentPaths);
}
}
Original CSV data and smart column splitting import result

PDF Table Import to Excel
PDF is the universal format for distribution and archiving, but the table data inside it cannot be edited directly: copying it into Excel misaligns rows and columns, loses merged cells, and turns numbers and dates into text. When suppliers, banks, or government agencies deliver reports in PDF, accurately restoring the table data into editable Excel is an essential step in moving from fixed-layout documents to electronic processing.
The following example uses the Spire.Agent.Office agent to automatically extract table data from a PDF and write it into Excel through natural language instructions:
using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Xls;
// PDF source file to be imported (passed as an attachment)
string[] attachmentPaths = new string[] { @"C:\DataImport\PurchaseOrder.pdf" };
// Save path of the import result document
string savePath = @"C:\DataImport\PurchaseOrderData.xlsx";
// SpireToken Key
string key = "sk-TF***************************r";
// Natural language instruction
string instruction =
"Process as follows:\n" +
"1. Convert the attached PDF file to an Excel document and apply appropriate formatting to improve readability\n" +
"2. Unify the formats of dates/sales amounts/phone numbers in the file\n" +
"3. Mark erroneous and missing data with a red background";
// AI generation
AIResult result = ImportPdfData(instruction, savePath, key, attachmentPaths);
// AI-assisted PDF import
static AIResult ImportPdfData(string instruction, string savePath, string key, string[] attachmentPaths)
{
// Configure the AI processing options
AIOptions options = new AIOptions();
options.SpireToken = key;
using (Workbook wb = new Workbook())
{
AIDocumentProcessor processor = wb.AI(options);
return processor.ExecuteInstruction(wb, instruction, savePath, attachmentPaths);
}
}
Original PDF data and table data extracted into Excel

Frequently Asked Questions
Inconsistent CSV delimiters / commas within fields cause column misalignment
Cause: The CSV delimiter may be a semicolon or a tab, or a field may contain a quoted comma or newline, which causes the whole row to shift when columns are split automatically.
Solution: Specify the delimiter in the instruction, or let the AI identify it automatically and correctly handle the quoted fields.
Numbers starting with 0 lose their leading zeros
Cause: Values starting with 0, such as phone numbers, ID numbers, and account numbers, are imported as numeric values, and the leading zeros are dropped.
Solution: Specify the relevant columns as text type in the instruction, such as "set the phone number and ID number columns to text format and preserve the leading zeros".
Obtaining a SpireToken Key
- Contact sales@e-iceblue.com or visit https://www.e-iceblue.com/TemLicense.html to obtain a trial/commercial API key
Configure it in code:
AIOptions options = new AIOptions();
options.SpireToken = key;