Adding charts to Excel files is one of the most common data visualization requirements in web applications. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It supports creating a wide variety of chart types, including column charts, pie charts, doughnut charts, line charts, scatter charts, and more.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Create a Column Chart

Column charts are one of the most commonly used chart types for comparing values across categories. With Spire.XLS for JavaScript, you can create a clustered column chart by first populating a worksheet with data, then adding a chart object, setting the chart type to ColumnClustered, and configuring the chart title, axes, and data labels. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric data.
  3. Add a chart to the worksheet using sheet.Charts.Add().
  4. Set the chart's DataRange to the data range and specify the chart type as ExcelChartType.ColumnClustered.
  5. Configure the chart position, title, axis titles, and legend.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a clustered column chart in React:

function App() {
  const createColumnChart = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    const sheet = workbook.Worksheets.get(0);
    sheet.Name = "ClusteredColumn";

    // Populate chart data
    sheet.Range.get("A1").Value = "Country";
    sheet.Range.get("A2").Value = "Cuba";
    sheet.Range.get("A3").Value = "Mexico";
    sheet.Range.get("A4").Value = "France";
    sheet.Range.get("A5").Value = "German";

    sheet.Range.get("B1").Value = "Jun";
    sheet.Range.get("B2").NumberValue = 6000;
    sheet.Range.get("B3").NumberValue = 8000;
    sheet.Range.get("B4").NumberValue = 9000;
    sheet.Range.get("B5").NumberValue = 8500;

    sheet.Range.get("C1").Value = "Aug";
    sheet.Range.get("C2").NumberValue = 3000;
    sheet.Range.get("C3").NumberValue = 2000;
    sheet.Range.get("C4").NumberValue = 2300;
    sheet.Range.get("C5").NumberValue = 4200;

    // Add a chart and set its data range
    const chart = sheet.Charts.Add();
    chart.DataRange = sheet.Range.get("A1:C5");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.LeftColumn = 1;
    chart.TopRow = 6;
    chart.RightColumn = 11;
    chart.BottomRow = 29;

    // Set the chart type to clustered column
    chart.ChartType = xlsModule.ExcelChartType.ColumnClustered;

    // Configure chart title
    chart.ChartTitle = "Sales market by country";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Configure axis titles
    chart.PrimaryCategoryAxis.Title = "Country";
    chart.PrimaryCategoryAxis.Font.IsBold = true;
    chart.PrimaryCategoryAxis.TitleArea.IsBold = true;

    chart.PrimaryValueAxis.Title = "Sales(in Dollars)";
    chart.PrimaryValueAxis.HasMajorGridLines = false;
    chart.PrimaryValueAxis.MinValue = 1000;
    chart.PrimaryValueAxis.TitleArea.IsBold = true;
    chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90;

    // Configure data labels: show numeric value on each data point
    for (let i = 0; i < chart.Series.Length; i++) {
      let cs = chart.Series.get(i);
      cs.Format.Options.IsVaryColor = true;
      cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; // Show value labels
    }

    // Set legend position
    chart.Legend.Position = xlsModule.LegendPositionType.Top;

    // Save the workbook
    const outputFileName = 'ClusteredColumn.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger 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>Create Clustered Column Chart</h1>
      <button onClick={createColumnChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Clustered column chart created with Spire.XLS for JavaScript

Clustered column chart created with Spire.XLS for JavaScript


Create a Pie Chart

Pie charts are ideal for displaying the proportional distribution of data across categories. With Spire.XLS for JavaScript, you can create a pie chart by specifying the chart type as Pie when adding the chart, then binding category labels and data values. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric values.
  3. Add a chart with ExcelChartType.Pie using sheet.Charts.Add().
  4. Set the chart data range and bind category labels and values.
  5. Configure the chart position, title, and data labels.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a pie chart in React:

function App() {
  const createPieChart = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    let sheet = workbook.Worksheets.get(0);
    sheet.Name = "Pie Chart";

    // Populate chart data
    sheet.Range.get("A1").Value = "Year";
    sheet.Range.get("A2").Value = "2002";
    sheet.Range.get("A3").Value = "2003";
    sheet.Range.get("A4").Value = "2004";
    sheet.Range.get("A5").Value = "2005";

    sheet.Range.get("B1").Value = "Sales";
    sheet.Range.get("B2").NumberValue = 4000;
    sheet.Range.get("B3").NumberValue = 6000;
    sheet.Range.get("B4").NumberValue = 7000;
    sheet.Range.get("B5").NumberValue = 8500;

    // Add a pie chart
    let chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.Pie });
    chart.DataRange = sheet.Range.get("B2:B5");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.LeftColumn = 1;
    chart.TopRow = 6;
    chart.RightColumn = 9;
    chart.BottomRow = 25;

    // Configure chart title
    chart.ChartTitle = "Sales by year";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Bind category labels and values
    let cs = chart.Series.get(0);
    cs.CategoryLabels = sheet.Range.get("A2:A5");
    cs.Values = sheet.Range.get("B2:B5");
    cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; // Show value labels

    chart.PlotArea.Fill.Visible = false;

    // Save the workbook
    const outputFileName = 'Pie.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger 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>Create Pie Chart</h1>
      <button onClick={createPieChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Pie chart created with Spire.XLS for JavaScript

Pie chart created with Spire.XLS for JavaScript


Create a Doughnut Chart

A doughnut chart is similar to a pie chart but with a hollow center, which can display multiple data series. With Spire.XLS for JavaScript, you can create a doughnut chart by setting the chart type to Doughnut and configuring percentage data labels. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric values.
  3. Add a chart and set its ChartType to ExcelChartType.Doughnut.
  4. Configure the chart position, title, and percentage data labels.
  5. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a doughnut chart in React:

function App() {
  const createDoughnutChart = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    let sheet = workbook.Worksheets.get(0);

    // Populate chart data
    sheet.Range.get("A1").Value = "Country";
    sheet.Range.get("A1").Style.Font.IsBold = true;
    sheet.Range.get("A2").Value = "Cuba";
    sheet.Range.get("A3").Value = "Mexico";
    sheet.Range.get("A4").Value = "France";
    sheet.Range.get("A5").Value = "German";
    sheet.Range.get("B1").Value = "Sales";
    sheet.Range.get("B1").Style.Font.IsBold = true;
    sheet.Range.get("B2").NumberValue = 6000;
    sheet.Range.get("B3").NumberValue = 8000;
    sheet.Range.get("B4").NumberValue = 9000;
    sheet.Range.get("B5").NumberValue = 8500;

    // Add a doughnut chart
    let chart = sheet.Charts.Add();
    chart.ChartType = xlsModule.ExcelChartType.Doughnut;
    chart.DataRange = sheet.Range.get("A1:B5");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.LeftColumn = 4;
    chart.TopRow = 2;
    chart.RightColumn = 12;
    chart.BottomRow = 22;

    // Configure chart title
    chart.ChartTitle = "Market share by country";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Show percentage data labels
    for (let i = 0; i < chart.Series.Count; i++) {
      chart.Series.get(i).DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;
    }

    // Set legend position
    chart.Legend.Position = xlsModule.LegendPositionType.Top;

    // Save the workbook
    const outputFileName = 'CreateDoughnutChart.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger 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>Create Doughnut Chart</h1>
      <button onClick={createDoughnutChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Doughnut chart created with Spire.XLS for JavaScript

Doughnut chart created with Spire.XLS for JavaScript


Chart Type Reference

The examples above covered column charts, pie charts, and doughnut charts. In addition, Spire.XLS supports all standard Excel chart types, which are defined in the Spire.Xls.ExcelChartType enumeration. The complete list of 81 chart types is as follows:

Chart Type Description
1. ColumnClustered Represents Clustered Column Chart
2. ColumnStacked Represents Stacked Column Chart
3. Column100PercentStacked Represents 100% Stacked Column Chart
4. Column3DClustered Represents 3D Clustered Column Chart
5. Column3DStacked Represents 3D Stacked Column Chart
6. Column3D100PercentStacked Represents 3D 100% Stacked Column Chart
7. Column3D Represents 3D Column Chart
8. BarClustered Represents Clustered Bar Chart
9. BarStacked Represents Stacked Bar Chart
10. Bar100PercentStacked Represents 100% Stacked Bar Chart
11. Bar3DClustered Represents 3D Clustered Bar Chart
12. Bar3DStacked Represents 3D Stacked Bar Chart
13. Bar3D100PercentStacked Represents 100% 3D Stacked Bar Chart
14. Line Represents Line Chart
15. LineStacked Represents Stacked Line Chart
16. Line100PercentStacked Represents 100% Stacked Line Chart
17. LineMarkers Represents Markers Line Chart
18. LineMarkersStacked Represents Stacked Markers Line Chart
19. LineMarkers100PercentStacked Represents 100% Stacked Markers Line Chart
20. Line3D Represents 3D Line Chart
21. Pie Represents Pie Chart
22. Pie3D = 21 Represents 3D Pie Chart
23. PieOfPie Represents Pie of Pie chart
24. PieExploded Represents Exploded Pie Chart
25. Pie3DExploded Represents 3D Exploded Pie Chart
26. PieBar Represents Bar Pie Chart
27. ScatterMarkers Represents Markers Scatter Chart
28. ScatterSmoothedLineMarkers Represents ScatterSmoothedLineMarkers Chart
29. ScatterSmoothedLine Represents ScatterSmoothedLine Chart
30. ScatterLineMarkers Represents ScatterLineMarkers Chart
31. ScatterLine Represents ScatterLine Chart
32. Area Represents Area Chart
33. AreaStacked Represents AreaStacked Chart
34. Area100PercentStacked Represents Area100PercentStacked Chart
35. Area3D Represents Area3D Chart
36. Area3DStacked Represents Area3DStacked Chart
37. Area3D100PercentStacked Represents Area3D100PercentStacked Chart
38. Doughnut Represents Doughnut Chart
39. DoughnutExploded Represents DoughnutExploded Chart
40. Radar Represents Radar Chart
41. RadarMarkers Represents RadarMarkers Chart
42. RadarFilled Represents RadarFilled Chart
43. Surface3D Represents Surface3D Chart
44. Surface3DNoColor Represents Surface3DNoColor Chart
45. SurfaceContour Represents SurfaceContour Chart
46. SurfaceContourNoColor Represents SurfaceContourNoColor Chart
47. Bubble Represents Bubble Chart
48. Bubble3D Represents Bubble3D Chart
49. StockHighLowClose Represents StockHighLowClose Chart
50. StockOpenHighLowClose Represents StockOpenHighLowClose Chart
51. StockVolumeHighLowClose Represents StockVolumeHighLowClose Chart
52. StockVolumeOpenHighLowClose Represents StockVolumeOpenHighLowClose Chart
53. CylinderClustered Represents CylinderClustered Chart
54. CylinderStacked Represents CylinderStacked Chart
55. Cylinder100PercentStacked Represents Cylinder100PercentStacked Chart
56. CylinderBarClustered Represents CylinderBarClustered Chart
57. CylinderBarStacked Represents CylinderBarStacked Chart
58. CylinderBar100PercentStacked Represents CylinderBar100PercentStacked Chart
59. Cylinder3DClustered Represents Cylinder3DClustered Chart
60. ConeClustered Represents ConeClustered Chart
61. ConeStacked Represents ConeStacked Chart
62. Cone100PercentStacked Represents Cone100PercentStacked Chart
63. ConeBarClustered Represents ConeBarClustered Chart
64. ConeBarStacked Represents ConeBarStacked Chart
65. ConeBar100PercentStacked Represents ConeBar100PercentStacked Chart
66. Cone3DClustered Represents Cone3DClustered Chart
67. PyramidClustered Represents PyramidClustered Chart
68. PyramidStacked Represents PyramidStacked Chart
69. Pyramid100PercentStacked Represents Pyramid100PercentStacked Chart
70. PyramidBarClustered Represents PyramidBarClustered Chart
71. PyramidBarStacked Represents PyramidBarStacked Chart
72. PyramidBar100PercentStacked Represents PyramidBar100PercentStacked Chart
73. Pyramid3DClustered Represents Pyramid3DClustered Chart
74. CombinationChart Represents Combination Chart
75. Funnel Represents Funnel Chart
76. WaterFall Represents Waterfall Chart
77. BoxAndWhisker Represents Box and Whisker Chart
78. Histogram Represents Histogram Chart
79. Pareto Represents Pareto Chart
80. TreeMap Represents Tree Map Chart
81. SunBurst Represents Sunburst Chart

FAQ

How to show values or percentages on pie/doughnut chart labels

Solution: Choose the appropriate label property based on your needs:

// Show value labels
cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; // Show value labels
// Or show percentage labels
cs.DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;

Legend in the generated Excel file is truncated or not fully displayed

Cause: The chart area is too small to accommodate all legend items, or the legend position setting causes overlap with the chart data area.

Solution: Increase the vertical range of the chart or adjust the legend position:

// Increase chart height
chart.BottomRow = 35;
// Or adjust legend position
chart.Legend.Position = xlsModule.LegendPositionType.Bottom;

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Digital signatures ensure the authenticity of an Excel file's source and verify that its content has not been tampered with. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required.

This article covers two core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Detect Whether an Excel File Is Signed

Before processing a signed Excel file, checking its signature status can prevent unintended operations. Spire.XLS provides the IsDigitallySigned property to determine whether a workbook contains digital signatures. The core process consists of three stages: first, load the font files and the target Excel file into the WASM virtual file system via FetchFileToVFS; then, instantiate a Workbook and load the file; finally, retrieve the signature status through the IsDigitallySigned property.

function App() {
  const detectDigitalSignature = 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 fonts and Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Detect if the workbook contains digital signatures
    const isSigned = workbook.IsDigitallySigned;

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Show the detection result
    alert(isSigned ? 'The file is signed' : 'The file is not signed');
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Detect Digital Signature</h1>
      <button onClick={detectDigitalSignature}>
        Detect
      </button>
    </div>
  );
}

export default App;

Detection result dialog showing whether the file is signed

Detection result dialog showing whether the file is signed


Remove Digital Signatures from an Excel File

In cases where signature information needs to be updated, certificates replaced, or digital authentication canceled, the existing digital signatures must be removed from the Excel file. Using Spire.XLS, the core process consists of three stages: first, load the font files and the signed Excel file into the WASM virtual file system via FetchFileToVFS; then, instantiate a Workbook and load the file, calling RemoveAllDigitalSignatures to remove all digital signatures from the workbook at once; finally, save the workbook file with signatures removed via SaveToFile.

function App() {
  const removeDigitalSignatures = 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 fonts and Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the signed workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Remove all digital signatures
    workbook.RemoveAllDigitalSignatures();

    // Save the workbook without signatures
    const outputFileName = 'SignatureRemoved.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Read the file from VFS and trigger 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>Remove Digital Signatures</h1>
      <button onClick={removeDigitalSignatures}>
        Remove Signatures
      </button>
    </div>
  );
}

export default App;

Output document after removing digital signatures

Output document after removing digital signatures


FAQ

Can I detect a signature on a specific worksheet instead of the entire workbook?

Cause: Digital signatures are applied to the entire workbook, not individual worksheets.

Solution: Digital signatures operate at the workbook level. It is not possible to detect or remove signatures on a single worksheet. Both IsDigitallySigned and RemoveAllDigitalSignatures are workbook-level methods.

How do I batch detect or remove signatures from multiple Excel files?

Cause: Real-world projects often involve processing large numbers of files, making manual processing inefficient.

Solution: Use a loop to process files in batch:

const files = ['report1.xlsx', 'report2.xlsx', 'report3.xlsx'];
for (const file of files) {
  await window.spire.FetchFileToVFS(file, '', dataPath);
  const wb = new xlsModule.Workbook();
  wb.LoadFromFile({ fileName: file });
  if (wb.IsDigitallySigned) {
    wb.RemoveAllDigitalSignatures();
  }
  wb.SaveToFile({ fileName: `unsigned_${file}`, version: xlsModule.ExcelVersion.Version2016 });
  wb.Dispose();
}

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Word templates are the foundation of enterprise business workflows. HR needs standard employment contracts and offer letters, sales teams need professional quotation and report templates, and administration needs unified meeting notices and certification documents. With the Word AI capabilities of Spire.Agent.Office, you simply describe the desired template style and content structure in natural language — for example, "Create a contract template with mail merge fields for 'Name, Position, Department, Salary, Start Date, End Date, Contract Type, Probation Period (months), Location'" and AI delivers the template directly.

Comparison with Traditional SDK API Approach

Traditional Spire.Office for .NET API Spire.Agent.Office
Development Approach Call APIs to build document structure line by line, paragraph by paragraph Describe template style and structure in natural language; AI automatically composes and generates the complete template document
Code Volume Hundreds of lines of document-building code per template Just 1 natural language instruction
Style Adjustment Font, color, border, and other styles require complex code-based formatting Simply describe in natural language
Template Flexibility Template structure changes require rewriting underlying document-building logic — high maintenance cost Adjust the instruction description, AI regenerates — flexibly responds to changing requirements

Several typical business scenario Word template examples:

For product installation and SpireToken configuration, please refer to Integrating Spire.Agent.Office in a .NET Project. The examples below assume Spire.Agent.Office is already installed and SpireToken is configured.


Word Employment Contract Template

The most commonly used employment contracts in HR departments all share a relatively fixed structure: title, party information, main body clauses, signature section, etc.

using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;

string inputPath = @"";
// Result document path
string savePath = @"employmentContract.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
    "Generate a Word employment contract template. " +
    "The main title is 'Employment Contract', in No. 2 font size, bold, and centered. " +
    "The body text uses Arial font throughout, in Small No. 4 font size (12pt), with a first-line indent of 2 characters per paragraph. " +
    "Add a light blue watermark with the text 'E-iceblue' throughout the entire document. " +
    "Include the following fields as mail merge fields: Name, Position/Department, Salary, Start Date, End Date, Contract Type, Probation Period (months), and Location. " +
    "The overall style should be formal and professional, suitable for legal document scenarios.";
// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);

// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
    // Create AI processor options instance
    AIOptions options = new AIOptions();
    options.SpireToken = key;
    // Create Word document object
    using (Document doc = new Document())  
    {
        if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
        {
            doc.LoadFromFile(inputPath);  
        }
        // Create AI document processor instance
         AIDocumentProcessor processor = doc.AI(options);  

        // Process the document according to the instruction and save the result to the specified path
        return processor.ExecuteInstruction(doc, instruction, savePath);
    }
}

Word employment Contract Template


Word Quotation Template

The most commonly used quotation templates in sales and business departments all share a relatively fixed structure: title, company information, client information, product quotation table, amount summary, quotation terms, signature section, etc.

using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;

string inputPath = @"";
// Result document path
string savePath = @"QuotationTemplate.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
    "Generate a professional quotation template with the following styling requirements: " +
    "Main title: 'Quotation' , font size equivalent to  26pt, bold, centered, using 'Arial' font. " +
    "Body text: Calibri font, size 12pt , with 1.5× line spacing. " +
    "Template structure must include: Company logo placeholder area, company information (address, phone number, email), client information (client name, contact person), product quotation table (including Serial Number, Product Name, Specifications, Quantity, Unit Price, Subtotal, Remarks), total price (in words + in digits), quotation validity period, company stamp/seal area. \n" +
    "Use {{ }} as placeholder markers throughout the template, for example: {{Company Name}}, {{Client Name}}, {{Product Name}}, {{Unit Price}}, {{Quantity}}, {{Subtotal}}, {{Total Price in Words}}, {{Total Price in Digits}}."; 

// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);

// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
    // Create AI processor options instance
    AIOptions options = new AIOptions();
    options.SpireToken = key;
    // Create Word document object
    using (Document doc = new Document())  
    {
        if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
        {
            doc.LoadFromFile(inputPath);  
        }
        // Create AI document processor instance
         AIDocumentProcessor processor = doc.AI(options);  

        // Process the document according to the instruction and save the result to the specified path
        return processor.ExecuteInstruction(doc, instruction, savePath);
    }
}

Word Quotation Template


Word Certificate Template

Certificate templates are widely used in scenarios such as training certification, commendation and awards, event participation, etc. Their core structure typically includes: certificate title (e.g., "Certificate of Honor", "Certificate of Completion"), certificate number, etc.

using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;

string inputPath = @"";
// Result document path
string savePath = @"WordCertificateTemplate.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
"Generate a one-page honor certificate template with the following style requirements: " +
"Overall classical and solemn style, with a gold double-line border, using Times New Roman font." +
"Centered at the top: certificate title 'CERTIFICATE OF HONOR' — 24pt, bold, gold color." +
"Center-aligned body layout with the following structure:" +
"  Line 1: 'This is to certify that';" +
"  Line 2: '{{Full Name}}' — bold, red color;" +
"  Line 3: 'has demonstrated outstanding performance during the {{Year}} work year and is hereby awarded:';" +
"  Line 4: '{{Honor Title}}' — bold, gold color;" +
"  Line 5: 'This certificate is presented in recognition of this achievement.'." +
"Signatory area: bottom right, two lines right-aligned: '{{Issuing Authority}}' and '{{Date}}'." +
"Bottom left: certificate number displayed as 'No.: {{Certificate Number}}'." +
"Overall style: formal, solemn, and dignified, suitable for government or corporate honorary certificate presentations.";

// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);

// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
    // Create AI processor options instance
    AIOptions options = new AIOptions();
    options.SpireToken = key;
    // Create Word document object
    using (Document doc = new Document())  
    {
        if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
        {
            doc.LoadFromFile(inputPath);  
        }
        // Create AI document processor instance
         AIDocumentProcessor processor = doc.AI(options);  

        // Process the document according to the instruction and save the result to the specified path
        return processor.ExecuteInstruction(doc, instruction, savePath);
    }
}

Word Certificate Template


Budget Report Template

Budget report templates are commonly used document tools in enterprises or organizations for financial planning, project proposals, and annual planning. Their core structure typically includes: report title (e.g., "XX Annual Budget Report", "XX Project Budget Plan"), preparing unit and date, budget preparation notes, etc.

using Spire.Agent.Office.AI;
using Spire.Agent.Office.Extensions;
using Spire.Doc;

string inputPath = @"";
// Result document path
string savePath = @"BudgetReportTemplate.docx"; ;
// SpireToken Key
string key = "s******************************r";
// Natural language instruction
string instruction =
"Generate a professional budget report template with the following style requirements:" +
"Main title: '{{Year}} Annual Budget Report' — font size No.1 (approx. 26pt), bold, centered, using Arial." +
"Add a subtitle below the title: 'Prepared by: {{Department Name}} | Date: {{Preparation Date}}', font size No.4 small (approx. 12pt), centered." +
"The body is divided into four sections:\n" +
"  Section 1 (Budget Overview): At the top, display four key metrics in a card-style horizontal layout with light background shading — 'Annual Budget Total: {{Total Budget}} ten-thousand yuan', 'Amount Executed: {{Executed Amount}} ten-thousand yuan', 'Execution Rate: {{Execution Rate}}%', 'Remaining Budget: {{Remaining Budget}} ten-thousand yuan'. The four data cards are placed side by side with numeric values bolded and enlarged.\n" +
"  Section 2 (Detailed Budget Table): A detailed budget table with columns — Account Code, Account Name, Annual Budget (ten-thousand yuan), Q1 Execution, Q2 Execution, Q3 Execution, Q4 Execution, Total Executed, Execution Rate (%), Remaining Budget (ten-thousand yuan). Table header: dark green background (#1E5631), white bold font; all numeric columns: retain two decimal places; data rows: alternating row colors.\n" +
"  Section 4 (Budget Notes): At the bottom of the page, add a 'Budget Notes' section — '{{Budget Preparation Notes}}'." +
"Overall style: formal, professional, and elegant — suitable for a formal budget report presented to management.";

// AI generation
AIResult result = ExecuteAIWord(instruction, inputPath, savePath, key);

// Word AI processing
static AIResult ExecuteAIWord(string instruction, string inputPath, string savePath, string key)
{
    // Create AI processor options instance
    AIOptions options = new AIOptions();
    options.SpireToken = key;
    // Create Word document object
    using (Document doc = new Document())  
    {
        if (!string.IsNullOrEmpty(inputPath) && File.Exists(inputPath))
        {
            doc.LoadFromFile(inputPath);  
        }
        // Create AI document processor instance
         AIDocumentProcessor processor = doc.AI(options);  

        // Process the document according to the instruction and save the result to the specified path
        return processor.ExecuteInstruction(doc, instruction, savePath);
    }
}

Budget Report Template


Frequently Asked Questions

Generated template style does not fully match expectations

Cause: The style description in the instruction is not specific enough.

Solution: Specify details such as font name explicitly in the instruction.

Already generated template needs modification

Cause: Business requirements have changed, requiring template adjustments.

Solution: Directly describe the modifications in the instruction and regenerate, or use the current document as input for AI secondary processing.

Generated template shows garbled Chinese characters or incorrect fonts

Cause: The font specified in the instruction is not installed on the system.

Solution: Ensure the font mentioned in the instruction is installed on the system, or use common system fonts in the instruction.


Getting a SpireToken Key

Configure in code:

AIOptions options = new AIOptions();
options.SpireToken = key;
Page 6 of 344
page 6