Export Excel files using server-side processing in Angular Spreadsheet

19 Nov 202624 minutes to read

The Angular Spreadsheet Editor component uses a server-assisted workflow to save Excel files efficiently and accurately. When a user saves an Excel file, the Spreadsheet content displayed in the browser is first serialized into a structured JSON workbook. This JSON includes all essential details-such as data, formulas, formatting, styles, and sheet configuration.

The JSON workbook is then sent to a server endpoint for processing. On the server, the Syncfusion.EJ2.Spreadsheet library is used to convert the JSON data into a fully formatted Excel file. This library is built on top of Syncfusion XlsIO, which itself is implemented using .NET Frameworks. The server parses the JSON, maps its contents to an XlsIO Workbook instance, and ensures that all data, styles, formulas, and other Spreadsheet features are accurately preserved.

For save processing, the Spreadsheet component serializes its content into a structured JSON workbook that includes all essential details-such as data, formulas, formatting, styles, and sheet configuration. This JSON is sent to the server where it is converted into a fully formatted Excel file using the Syncfusion XlsIO library.

Since the server is responsible for generating the final Excel file, the total export time can vary depending on the workbook’s complexity. Factors such as the level of formatting, styles, and the use of advanced features like formulas or conditional formatting can influence processing time. After the file is successfully generated, it is sent back to the client for download.

Hosted Syncfusion Service URLs

In the code samples and demos, you may see Syncfusion-hosted service URLs used for the saveUrl property. These URLs point to Syncfusion’s own WebAPI services (built with ASP.NET Core) that handle saving Excel files. These hosted URLs are provided only for demonstration and evaluation purposes:

Hosted Syncfusion Service URLs:

openUrl='https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/open'
saveUrl='https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save'

For your own development and production, you must set up your own web service for save operations. This ensures your data remains private, secure, and fully under your control. Using your own service also allows you to customize processing, apply business logic, and comply with your organization’s security requirements.

Server Configuration

Below is an example of a server-side Save endpoint using ASP.NET Core WebAPI, which is the same approach used for building the hosted Syncfusion URLs. This endpoint receives the Spreadsheet data as JSON, processes it with the Syncfusion Spreadsheet library, and returns the generated Excel file to the client:

// Save action
[HttpPost]
[Route("Save")]
public IActionResult Save([FromForm] SaveSettings saveSettings)
{
    if (saveSettings != null && !string.IsNullOrEmpty(saveSettings.JSONData)) {
        return Workbook.Save(saveSettings);
    }
    return BadRequest("saveSettings or JSONData was not available.");
}

Note: For details on how to set up your own web service for open/save operations, refer to the web service section of this documentation.

Install Required Dependencies

For spreadsheet open and save operations, install the following NuGet packages based on your server platform:

Platform Assembly NuGet Package
ASP.NET Core Syncfusion.EJ2.Spreadsheet.AspNet.Core
Syncfusion.EJ2.AspNet.Core
Syncfusion.XlsIORenderer.Net.Core
Syncfusion.EJ2.Spreadsheet.AspNet.Core
Syncfusion.EJ2.AspNet.Core
Syncfusion.XlsIORenderer.Net.Core
ASP.NET MVC5 Syncfusion.XlsIO.AspNet.Mvc5
Syncfusion.ExcelToPdfConverter.AspNet.Mvc5
Syncfusion.Pdf.AspNet.Mvc5
Syncfusion.ExcelChartToImageConverter.AspNet.Mvc5
Syncfusion.EJ2.MVC5
Syncfusion.XlsIO.AspNet.Mvc5
Syncfusion.ExcelToPdfConverter.AspNet.Mvc5
Syncfusion.Pdf.AspNet.Mvc5
Syncfusion.ExcelChartToImageConverter.AspNet.Mvc5
Syncfusion.EJ2.MVC5

For more details, see the dependencies section on nuget.org.

To enable saving Excel files, set the allowSave property to true and specify the service URL using the saveUrl property. When a save action is triggered, the control sends the spreadsheet model to this endpoint, where it is processed and returned as a downloadable Excel file.

For a quick walkthrough on how the save functionality works, refer to the following video:

UI options to Save Excel files

In user interface, you can save Spreadsheet data as Excel document by clicking File > Save As menu item in ribbon.

The following sample shows the Save option by using the saveUrl property in the Spreadsheet control. You can also use the beforeSave event to customize or cancel the save action which gets triggered before saving the Spreadsheet as an Excel file.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { DropDownButtonModule } from '@syncfusion/ej2-angular-splitbuttons'
import { SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet'



import { Component } from '@angular/core';
import { SpreadsheetComponent, BeforeSaveEventArgs } from '@syncfusion/ej2-angular-spreadsheet';

@Component({
imports: [
        
        DropDownButtonModule,
        SpreadsheetAllModule
    ],


standalone: true,
    selector: 'app-container',
    template: "<ejs-spreadsheet (beforeSave)='beforeSave($event)' saveUrl='https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save' allowSave='true'> </ejs-spreadsheet>"
})
export class AppComponent {
     beforeSave (args: BeforeSaveEventArgs) {
        // your code snippets here
    }
 }
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Please find the below table for the beforeSave event arguments.

Parameter Type Description
url string Specifies the save url.
fileName string Specifies the file name.
saveType SaveType Specifies the saveType like Xlsx, Xls, Csv and Pdf.
customParams object Passing the custom parameters from client to server while performing save operation.
isFullPost boolean It sends the form data from client to server, when set to true. It fetches the data from client to server and returns the data from server to client, when set to false.
needBlobData boolean You can get the blob data if set to true.
cancel boolean To prevent the save operations.
  • Use Ctrl + S keyboard shortcut to save the Spreadsheet data as Excel file.
  • The default value of allowSave property is true. For demonstration purpose, we have showcased the allowSave property in previous code snippet.
  • Demo purpose only, we have used the online web service url link.

Save Excel files programmatically

To save Excel files programmatically in the Spreadsheet, you can use the save method of the Spreadsheet component. Before invoking this method, ensure that the saveUrl property is properly configured, as it is required for processing and generating the file on the server.

Please find the below table for the save method arguments.

Parameter Type Description
options SaveOptions Options for saving the workbook.
jsonConfig (optional) SerializationOptions Specify the serialization options to customize the exported JSON data.

The following code example demonstrates how to save an Excel file programmatically in the Spreadsheet.

import { Component, ViewChild } from '@angular/core';
import { SpreadsheetComponent, SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SpreadsheetAllModule],
  template: `<ejs-spreadsheet #spreadsheet [saveUrl]="saveUrl"></ejs-spreadsheet>
<button type="button" (click)="save()">Save</button>`
})
export class AppComponent {
  @ViewChild('spreadsheet') public spreadsheet!: SpreadsheetComponent;
  public saveUrl = 'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save';
  public save(): void {
    this.spreadsheet.save({ fileName: 'Worksheet', saveType: 'Xlsx' });
  }
}

Supported Excel file formats for Save

The following file formats are supported when saving the Spreadsheet component:

  • Microsoft Excel Workbook (.xlsx)
  • Microsoft Excel 97–2003 Workbook (.xls)
  • Comma-Separated Values (.csv)
  • Portable Document Format (.pdf)

Export options

Save Excel files as Blob

By default, the Spreadsheet control saves the Excel file and downloads it to the local file system. If you want to save an Excel file as blob data, you need to set needBlobData property to true and isFullPost property to false in the beforeSave event of the spreadsheet. Subsequently, you will receive the spreadsheet data as a blob in the saveComplete event. You can then post the blob data to the server endpoint for saving.

Please find below the code to retrieve blob data from the Spreadsheet control below.

import { NgModule, ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { BeforeSaveEventArgs, SaveCompleteEventArgs, SpreadsheetAllModule, SpreadsheetComponent, created } from '@syncfusion/ej2-angular-spreadsheet'
import { Component } from '@angular/core';
import { getDefaultData } from './datasource';

@Component({
  imports: [

    SpreadsheetAllModule
  ],
  standalone: true,
  selector: 'app-container',
  template: `<div class="control-section">
  <ejs-spreadsheet #spreadsheet openUrl="https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/open" saveUrl = 'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save' (beforeSave)="beforeSave($event)" (saveComplete)="saveComplete($event)">
        <e-sheets>
            <e-sheet name="Car Sales Report">
                <e-ranges>
                    <e-range [dataSource]="data"></e-range>
                </e-ranges>
                <e-columns>
                    <e-column [width]=180></e-column>
                    <e-column [width]=130></e-column>
                    <e-column [width]=130></e-column>
                    <e-column [width]=180></e-column>
                    <e-column [width]=130></e-column>
                    <e-column [width]=120></e-column>
                </e-columns>
            </e-sheet>
        </e-sheets>
    </ejs-spreadsheet>
</div>`
})
export class AppComponent {
  constructor() {

  }
  
  @ViewChild('spreadsheet')
  
  public spreadsheetObj!: SpreadsheetComponent;
  public data: Object[] = getDefaultData();

    beforeSave(args: BeforeSaveEventArgs): void {
        args.needBlobData = true; // To trigger the saveComplete event.
        args.isFullPost = false; // Get the spreadsheet data as blob data in the saveComplete event.
    };
    saveComplete(args: SaveCompleteEventArgs): void {
        // To obtain the Blob data.
        console.log("Spreadsheet BlobData: ", args.blobData)
    };
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js'
bootstrapApplication(AppComponent)
  .catch((err) => console.error(err));

Save Workbook as JSON

Our Spreadsheet component allows you to export an entire workbook as a JSON object. This JSON output includes all workbook details such as sheets, cell values, formulas, styles, and formatting.

You can optionally pass serialization options to the saveAsJson method to exclude specific features from the exported JSON. For example, you can choose to ignore styles, formulas, number formats, images, or conditional formatting. These options are fully optional-if they are not provided, the method exports the workbook with all details preserved by default.

The following example demonstrates how to save a workbook as JSON from the Spreadsheet component.

import { NgModule, ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { SpreadsheetAllModule, SpreadsheetComponent, SerializationOptions } from '@syncfusion/ej2-angular-spreadsheet'
import { createElement } from '@syncfusion/ej2-base';
import { Component } from '@angular/core';

@Component({
  imports: [

    SpreadsheetAllModule
  ],
  standalone: true,
  selector: 'app-container',
  template: `<div class="control-section">
  <div id="Saveasjson">
        <label id="Heading">Save As Json Options:</label> <br>
        <input type="checkbox" id="valueOnly" (change)="toggleCheckboxes()"><label for="valueOnly">Only Values</label>
        <input type="checkbox" id="style"><label for="style">Ignore Style</label>
        <input type="checkbox" id="formula"><label for="formula">Ignore Formula</label>
        <input type="checkbox" id="format"><label for="format">Ignore Format</label>
        <input type="checkbox" id="cf"><label for="cf">Ignore CF</label>
        <input type="checkbox" id="dv"><label for="dv">Ignore Validation</label>
        <input type="checkbox" id="freeze"><label for="freeze">Ignore Freezepane</label>
        <input type="checkbox" id="wrap"><label for="wrap">Ignore Wrap</label>
        <input type="checkbox" id="chart"><label for="chart">Ignore Chart</label>
        <input type="checkbox" id="image"><label for="image">Ignore Image</label>
        <input type="checkbox" id="note"><label for="note">Ignore Note</label>
        <button class="e-btn" (click)="saveFile()">Save with JSON Serialization</button>
    </div>
    <ejs-spreadsheet #spreadsheet [openUrl]="openUrl" ></ejs-spreadsheet>
</div>`
})
export class AppComponent {
  constructor() {
      
  }
  @ViewChild('spreadsheet')
  public spreadsheetObj!: SpreadsheetComponent;
  public openUrl = 'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/open';

  createOptions() {
      const options: SerializationOptions = {};
      options.ignoreStyle = (document.getElementById('style') as HTMLInputElement).checked;
      options.ignoreFormula = (document.getElementById('formula') as HTMLInputElement).checked;
      options.ignoreFormat = (document.getElementById('format') as HTMLInputElement).checked;
      options.ignoreConditionalFormat = (document.getElementById('cf') as HTMLInputElement).checked;
      options.ignoreValidation = (document.getElementById('dv') as HTMLInputElement).checked;
      options.ignoreFreezePane = (document.getElementById('freeze') as HTMLInputElement).checked;
      options.ignoreWrap = (document.getElementById('wrap') as HTMLInputElement).checked;
      options.ignoreChart = (document.getElementById('chart') as HTMLInputElement).checked;
      options.ignoreImage = (document.getElementById('image') as HTMLInputElement).checked;
      options.ignoreNote = (document.getElementById('note') as HTMLInputElement).checked;
      return options;
  }
  toggleCheckboxes() {
      let valueOnlyCheckbox: HTMLInputElement = document.getElementById('valueOnly') as HTMLInputElement;
      let checkboxes: NodeListOf<Element> = document.querySelectorAll('#Saveasjson input[type="checkbox"]:not(#valueOnly)');
      checkboxes.forEach(checkbox => {
          (checkbox as HTMLInputElement).disabled = valueOnlyCheckbox.checked;
          if (valueOnlyCheckbox.checked) {
              (checkbox as HTMLInputElement).checked = false;
          }
      });
  }
  saveFile() {
      let valueOnlyCheckbox: boolean = (document.getElementById("valueOnly") as HTMLInputElement).checked;
      let options: SerializationOptions = valueOnlyCheckbox ? { onlyValues: true } : this.createOptions();
      this.spreadsheetObj.saveAsJson(options).then((response: any) => {
          let formData: FormData = new FormData();
          formData.append(
              'JSONData',
              JSON.stringify(response.jsonObject.Workbook)
          );
          formData.append('fileName', 'Sample');
          formData.append('saveType', 'Xlsx');
          formData.append('pdfLayoutSettings', JSON.stringify({ fitSheetOnOnePage: false, orientation: 'Portrait' })),
              fetch(
                  'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save',
                  {
                      method: 'POST',
                      body: formData,
                  }
              ).then((response) => {
                  response.blob().then((data) => {
                      let anchor: HTMLElement | any = createElement('a', {
                          attrs: { download: 'Sample.xlsx' },
                      });
                      let url: string = URL.createObjectURL(data);
                      anchor.href = url;
                      document.body.appendChild(anchor);
                      anchor.click();
                      URL.revokeObjectURL(url);
                      document.body.removeChild(anchor);
                  });
              });
      });
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js'
bootstrapApplication(AppComponent)
  .catch((err) => console.error(err));

Save Excel files to a server

By default, the Spreadsheet control saves the Excel file and downloads it to the local file system. If you want to save an Excel file to a server location, you need to configure the server endpoint to convert the spreadsheet data into a file stream and save it to the server location. To do this, first, on the client side, you must convert the spreadsheet data into JSON format using the saveAsJson method and send it to the server endpoint. On the server endpoint, you should convert the received spreadsheet JSON data into a file stream using Syncfusion.EJ2.Spreadsheet.AspNet.Core, then convert the stream into an Excel file, and finally save it to the server location.

Client Side:

Place this code inside a component method after the Spreadsheet is created.

    // Convert the spreadsheet workbook to JSON data.
    this.spreadsheet.saveAsJson().then((json) => {
        const formData = new FormData();
        formData.append('FileName', "Sample");
        formData.append('saveType', 'Xlsx');
        // Passing the JSON data to perform the save operation.
        formData.append('JSONData', JSON.stringify(json.jsonObject.Workbook));
        formData.append('PdfLayoutSettings', JSON.stringify({ FitSheetOnOnePage: false }));
        // Using fetch to invoke the save process.
        fetch('https://localhost:{Your port number}/Home/Save', {
            method: 'POST',
            body: formData
        }).then((response) => {
            console.log(response);
        });
    });

Server Endpoint:

    public string Save(SaveSettings saveSettings)
    {
        try
        {
            // Save the workbook as stream.
            Stream fileStream = Workbook.Save<Stream>(saveSettings);
            // You can also save the stream file in your server location.
            string basePath = _env.ContentRootPath + "\\Files\\" + saveSettings.FileName + ".xlsx";
            var file = System.IO.File.Create(basePath);
            fileStream.Seek(0, SeekOrigin.Begin);
            // Copy the workbook stream to the file on the server.
            fileStream.CopyTo(file);
            file.Dispose();
            fileStream.Dispose();
            return string.Empty;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

You can find the server endpoint code to save the spreadsheet data as an Excel file in this attachment. After launching the server endpoint, you need to update the URL on the client side sample as shown below.

//To save an Excel file to the server.
fetch('https://localhost:{port number}/Home/Save')

Save Excel files with AWS Lambda

Before proceeding with the save process, you should deploy the spreadsheet open/save web API service in AWS Lambda. To host the open/save web service in the AWS Lambda environment, please refer to the following KB documentation.

How to deploy a spreadsheet open and save web API service to AWS Lambda

After deployment, you will get the AWS service URL for the open and save actions. Before saving the Excel file with this hosted save URL, you need to prevent the default save action to avoid getting a corrupted excel file on the client end. The save service returns the file stream as a result to the client, which can cause the file to become corrupted. To prevent this, set the args.cancel value to true in the beforeSave event. After that, convert the spreadsheet data into JSON format using the saveAsJson method in the beforeSave event and send it to the save service endpoint URL using a fetch request.

On the server side, the save service will take the received JSON data, pass it to the workbook Save method, and return the result as a base64 string. The fetch success callback will receive the Excel file in base64 string format on the client side. Finally, you can then convert the base64 string back to a file on the client end to obtain a non-corrupted Excel file.

The following code example shows how to save an Excel file using a hosted web service in AWS Lambda, as mentioned above.

import { Component, ViewChild } from '@angular/core';
import { SpreadsheetComponent, SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SpreadsheetAllModule],
  template: `<ejs-spreadsheet #spreadsheet [saveUrl]="saveUrl" (beforeSave)="beforeSaveHandler($event)"></ejs-spreadsheet>`
})
export class AppComponent {
  @ViewChild('spreadsheet') public spreadsheet!: SpreadsheetComponent;
  public saveUrl = 'https://your-api.execute-api.your-region.amazonaws.com/Prod/api/spreadsheet/save';
  private saveInitiated = false;
  public async beforeSaveHandler(args: any): Promise<void> {
    // saveAsJson also triggers beforeSave; let that nested event proceed without starting another save.
    if (this.saveInitiated) return;
    // Prevent the default save action.
    args.cancel = true;
    this.saveInitiated = true;
    try {
      // Convert the spreadsheet workbook to JSON data.
      const json = await this.spreadsheet.saveAsJson();
      const formData = new FormData();
      // Pass the workbook JSON to the server for save processing.
      formData.append('JSONData', JSON.stringify((json as any).jsonObject.Workbook));
      formData.append('saveType', 'Xlsx');
      formData.append('fileName', args.fileName || 'Worksheet');
      // Invoke the AWS service to generate the Excel file.
      const response = await fetch(this.saveUrl, { method: 'POST', body: formData });
      if (!response.ok) throw new Error('Save request failed.');
      // Read the Excel file returned by the service as Base64 text.
      const base64 = await response.text();
      // Remove any data URL prefix and decode the Base64 content into bytes.
      const bytes = Uint8Array.from(atob(base64.replace(/^data:.*?;base64,/, '')), (char) => char.charCodeAt(0));
      // Create a Blob with the XLSX content type from the decoded bytes.
      const blob = new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = (args.fileName || 'Worksheet') + '.xlsx';
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      URL.revokeObjectURL(url);
    } finally {
      this.saveInitiated = false;
    }
  }
}
public string Save([FromForm]SaveSettings saveSettings)
{
    // This will return the Excel in base64 string format.
    return Workbook.Save<string>(saveSettings);
}

Save Spreadsheet data as Base64 string

In the Spreadsheet component, there is currently no direct option to save data as a Base64 string. You can achieve this by saving the Spreadsheet data as blob data and then converting that saved blob data to a Base64 string using FileReader.

You can get the Spreadsheet data as blob in the saveComplete event when you set the needBlobData as true and isFullPost as false in the beforeSave event.

The following code example shows how to save the spreadsheet data as base64 string.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { SpreadsheetModule } from '@syncfusion/ej2-angular-spreadsheet'

import { Component, ViewChild } from '@angular/core';
import { SpreadsheetComponent, BeforeSaveEventArgs, SaveCompleteEventArgs } from '@syncfusion/ej2-angular-spreadsheet';
import { data } from './datasource';

@Component({
imports: [
        
        SpreadsheetModule
    ],


standalone: true,
    selector: 'app-container',
    template: `<div class="control-section">
    <button class="e-btn custom-btn" (click)='import()'>Import Base64</button>
    <button class="e-btn custom-btn" (click)='export()'>Export as Base64</button>
    <ejs-spreadsheet #spreadsheet openUrl="https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/open" (beforeSave)="beforeSave($event)" (saveComplete)="saveComplete($event)">
        <e-sheets>
            <e-sheet name="Car Sales Report">
                <e-ranges>
                    <e-range [dataSource]="data"></e-range>
                </e-ranges>
                <e-columns>
                    <e-column [width]=180></e-column>
                    <e-column [width]=130></e-column>
                    <e-column [width]=130></e-column>
                    <e-column [width]=180></e-column>
                    <e-column [width]=130></e-column>
                    <e-column [width]=120></e-column>
                </e-columns>
            </e-sheet>
        </e-sheets>
    </ejs-spreadsheet>
</div>`
})
export class AppComponent {
    @ViewChild('spreadsheet')
    spreadsheetObj!: SpreadsheetComponent;

    data: Object[] = data;
    base64String!: string | ArrayBuffer;
    beforeSave(args: BeforeSaveEventArgs): void {
        args.needBlobData = true; // To trigger the saveComplete event.
        args.isFullPost = false; // Get the spreadsheet data as blob data in the saveComplete event.
    };
    saveComplete(args: SaveCompleteEventArgs): void {
        // Convert blob data to base64 string.
        let reader: FileReader = new FileReader();
        reader.readAsDataURL(args.blobData);

        reader.onloadend = () => {
            this.base64String = reader.result ? reader.result : '';
        };
    };
    import(): void {
        fetch(this.base64String as string)
            .then((response) => response.blob())
            .then((fileBlob) => {
                let file: File = new File([fileBlob], 'Sample.xlsx');
                this.spreadsheetObj.open({ file: file });
            });
    };
    export(): void {
        this.spreadsheetObj.save({
            url: 'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save',
            fileName: 'Worksheet',
            saveType: 'Xlsx',
        }); // Specifies the save URL, file name, file type need to be saved.
        // Logs base64 string into the console.
        console.log('Base64 String - ', this.base64String);
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Advanced Save options

Configure JSON serialization

Previously, when saving the Spreadsheet as a workbook JSON object using the saveAsJson method, the entire workbook with all loaded features were processed and saved as a JSON object.

Now, you have the option to selectively ignore some features while saving the Spreadsheet as a JSON object by configuring serialization options and passing them as arguments to the saveAsJson method. This argument is optional, and if not configured, the entire workbook JSON object will be saved without ignoring any features.

spreadsheet.saveAsJson({ onlyValues: true });
Options Description
onlyValues If true, includes only the cell values in the JSON output.
ignoreStyle If true, excludes styles from the JSON output.
ignoreFormula If true, excludes formulas from the JSON output.
ignoreFormat If true, excludes number formats from the JSON output.
ignoreConditionalFormat If true, excludes conditional formatting from the JSON output.
ignoreValidation If true, excludes data validation rules from the JSON output.
ignoreFreezePane If true, excludes freeze panes from the JSON output.
ignoreWrap If true, excludes text wrapping settings from the JSON output.
ignoreChart If true, excludes charts from the JSON output.
ignoreImage If true, excludes images from the JSON output.
ignoreNote If true, excludes notes from the JSON output.

The following code snippet demonstrates how to configure the serialization options and pass them as arguments to the saveAsJson method:

import { NgModule, ViewChild } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { SpreadsheetAllModule, SpreadsheetComponent, SerializationOptions } from '@syncfusion/ej2-angular-spreadsheet'
import { createElement } from '@syncfusion/ej2-base';
import { Component } from '@angular/core';

@Component({
  imports: [

    SpreadsheetAllModule
  ],
  standalone: true,
  selector: 'app-container',
  template: `<div class="control-section">
  <div id="Saveasjson">
        <label id="Heading">Save As Json Options:</label> <br>
        <input type="checkbox" id="valueOnly" (change)="toggleCheckboxes()"><label for="valueOnly">Only Values</label>
        <input type="checkbox" id="style"><label for="style">Ignore Style</label>
        <input type="checkbox" id="formula"><label for="formula">Ignore Formula</label>
        <input type="checkbox" id="format"><label for="format">Ignore Format</label>
        <input type="checkbox" id="cf"><label for="cf">Ignore CF</label>
        <input type="checkbox" id="dv"><label for="dv">Ignore Validation</label>
        <input type="checkbox" id="freeze"><label for="freeze">Ignore Freezepane</label>
        <input type="checkbox" id="wrap"><label for="wrap">Ignore Wrap</label>
        <input type="checkbox" id="chart"><label for="chart">Ignore Chart</label>
        <input type="checkbox" id="image"><label for="image">Ignore Image</label>
        <input type="checkbox" id="note"><label for="note">Ignore Note</label>
        <button class="e-btn" (click)="saveFile()">Save with JSON Serialization</button>
    </div>
    <ejs-spreadsheet #spreadsheet [openUrl]="openUrl" ></ejs-spreadsheet>
</div>`
})
export class AppComponent {
  constructor() {
      
  }
  @ViewChild('spreadsheet')
  public spreadsheetObj!: SpreadsheetComponent;
  public openUrl = 'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/open';

  createOptions() {
      const options: SerializationOptions = {};
      options.ignoreStyle = (document.getElementById('style') as HTMLInputElement).checked;
      options.ignoreFormula = (document.getElementById('formula') as HTMLInputElement).checked;
      options.ignoreFormat = (document.getElementById('format') as HTMLInputElement).checked;
      options.ignoreConditionalFormat = (document.getElementById('cf') as HTMLInputElement).checked;
      options.ignoreValidation = (document.getElementById('dv') as HTMLInputElement).checked;
      options.ignoreFreezePane = (document.getElementById('freeze') as HTMLInputElement).checked;
      options.ignoreWrap = (document.getElementById('wrap') as HTMLInputElement).checked;
      options.ignoreChart = (document.getElementById('chart') as HTMLInputElement).checked;
      options.ignoreImage = (document.getElementById('image') as HTMLInputElement).checked;
      options.ignoreNote = (document.getElementById('note') as HTMLInputElement).checked;
      return options;
  }
  toggleCheckboxes() {
      let valueOnlyCheckbox: HTMLInputElement = document.getElementById('valueOnly') as HTMLInputElement;
      let checkboxes: NodeListOf<Element> = document.querySelectorAll('#Saveasjson input[type="checkbox"]:not(#valueOnly)');
      checkboxes.forEach(checkbox => {
          (checkbox as HTMLInputElement).disabled = valueOnlyCheckbox.checked;
          if (valueOnlyCheckbox.checked) {
              (checkbox as HTMLInputElement).checked = false;
          }
      });
  }
  saveFile() {
      let valueOnlyCheckbox: boolean = (document.getElementById("valueOnly") as HTMLInputElement).checked;
      let options: SerializationOptions = valueOnlyCheckbox ? { onlyValues: true } : this.createOptions();
      this.spreadsheetObj.saveAsJson(options).then((response: any) => {
          let formData: FormData = new FormData();
          formData.append(
              'JSONData',
              JSON.stringify(response.jsonObject.Workbook)
          );
          formData.append('fileName', 'Sample');
          formData.append('saveType', 'Xlsx');
          formData.append('pdfLayoutSettings', JSON.stringify({ fitSheetOnOnePage: false, orientation: 'Portrait' })),
              fetch(
                  'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save',
                  {
                      method: 'POST',
                      body: formData,
                  }
              ).then((response) => {
                  response.blob().then((data) => {
                      let anchor: HTMLElement | any = createElement('a', {
                          attrs: { download: 'Sample.xlsx' },
                      });
                      let url: string = URL.createObjectURL(data);
                      anchor.href = url;
                      document.body.appendChild(anchor);
                      anchor.click();
                      URL.revokeObjectURL(url);
                      document.body.removeChild(anchor);
                  });
              });
      });
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js'
bootstrapApplication(AppComponent)
  .catch((err) => console.error(err));

Customization

Pass custom parameters during Save

Passing the custom parameters from client to server by using beforeSave event.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { DropDownButtonModule } from '@syncfusion/ej2-angular-splitbuttons'
import { SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet'



import { Component, OnInit } from '@angular/core';
import { SpreadsheetComponent, BeforeSaveEventArgs } from '@syncfusion/ej2-angular-spreadsheet';
import { data } from './datasource';

@Component({
imports: [
        
        DropDownButtonModule,
        SpreadsheetAllModule
    ],


standalone: true,
    selector: 'app-container',
    template: "<ejs-spreadsheet #spreadsheet (beforeSave)='beforeSave($event)' saveUrl='https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save' allowSave='true'> <e-sheets> <e-sheet> <e-ranges> <e-range [dataSource]='data'></e-range></e-ranges><e-columns><e-column [width]=90></e-column><e-column [width]=100></e-column><e-column [width]=96></e-column><e-column [width]=120></e-column><e-column [width]=130></e-column><e-column [width]=120></e-column></e-columns></e-sheet></e-sheets></ejs-spreadsheet>"
})
export class AppComponent implements OnInit {
    public data?: object[];
    ngOnInit(): void {
        this.data = data;
    }
    beforeSave (args: BeforeSaveEventArgs) {
        args.customParams = { customParams: 'you can pass custom params in server side'}; // you can pass the custom params
    }
 }
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Server side code snippets:

    public IActionResult Save(SaveSettings saveSettings, string customParams)
        {
            Console.WriteLine(customParams); // you can get the custom params in controller side
            return Workbook.Save(saveSettings);
        }

Add custom headers to Save requests

You can add your own custom header to the save action in the Spreadsheet. For processing the data, it has to be sent from client to server side and adding customer header can provide privacy to the data with the help of Authorization Token. Through the fileMenuItemSelect event, the custom header can be added to the request during save action.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { DropDownButtonModule } from '@syncfusion/ej2-angular-splitbuttons'
import { SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet'



import { Component, OnInit, ViewChild } from '@angular/core';
import { MenuSelectEventArgs, SpreadsheetComponent } from '@syncfusion/ej2-angular-spreadsheet';
import { createElement } from '@syncfusion/ej2-base';
import { data } from './datasource';

@Component({
imports: [
        
        DropDownButtonModule,
        SpreadsheetAllModule
    ],


standalone: true,
    selector: 'app-container',
    template: "<ejs-spreadsheet #spreadsheet (fileMenuItemSelect)='onFileItemSelect($event)' saveUrl='https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save' allowSave='true'> <e-sheets> <e-sheet> <e-ranges> <e-range [dataSource]='data'></e-range></e-ranges><e-columns><e-column [width]=90></e-column><e-column [width]=100></e-column><e-column [width]=96></e-column><e-column [width]=120></e-column><e-column [width]=130></e-column><e-column [width]=120></e-column></e-columns></e-sheet></e-sheets></ejs-spreadsheet>"
})
export class AppComponent implements OnInit {
    public data: object[] | undefined;
  @ViewChild('spreadsheet') public spreadsheetObj!: SpreadsheetComponent;
  ngOnInit(): void {
    this.data = data;
  }
  onFileItemSelect(args: MenuSelectEventArgs) {
    if (args.item.text === 'Microsoft Excel') {
      args.cancel = true;
      this.spreadsheetObj
        .saveAsJson()
        .then((response: any) => {
          let formData: FormData = new FormData();
          formData.append(
            'JSONData',
            JSON.stringify(response.jsonObject.Workbook)
          );
          formData.append('fileName', 'Sample');
          formData.append('saveType', 'Xlsx');
          formData.append('pdfLayoutSettings', JSON.stringify({ fitSheetOnOnePage: false, orientation: 'Portrait' })),
          fetch(
            'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save',
            {
              method: 'POST',
              headers: { Authorization: 'YOUR TEXT' },
              body: formData,
            }
          ).then((response) => {
            response.blob().then((data) => {
              let anchor: HTMLElement = createElement('a', {
                attrs: { download: 'Sample.xlsx' },
              });
              let url = URL.createObjectURL(data);
              (anchor as HTMLAnchorElement).href = url;
              document.body.appendChild(anchor);
              anchor.click();
              URL.revokeObjectURL(url);
              document.body.removeChild(anchor);
            });
          });
        });
    }
  }
 }
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

Customize PDF export orientation

By default, the PDF document is created in Portrait orientation. You can change the orientation of the PDF document by using the args.pdfLayoutSettings.orientation argument settings in the beforeSave event.

The possible values are:

  • Portrait - Used to display content in a vertical layout.
  • Landscape - Used to display content in a horizontal layout.
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { DropDownButtonModule } from '@syncfusion/ej2-angular-splitbuttons'
import { SpreadsheetAllModule } from '@syncfusion/ej2-angular-spreadsheet'



import { Component, OnInit } from '@angular/core';
import { SpreadsheetComponent, BeforeSaveEventArgs } from '@syncfusion/ej2-angular-spreadsheet';
import { data } from './datasource';

@Component({
imports: [
        
        DropDownButtonModule,
        SpreadsheetAllModule
    ],


standalone: true,
    selector: 'app-container',
    template: "<ejs-spreadsheet #spreadsheet (beforeSave)='beforeSave($event)' saveUrl='https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save' allowSave='true'> <e-sheets> <e-sheet> <e-ranges> <e-range [dataSource]='data'></e-range></e-ranges><e-columns><e-column [width]=90></e-column><e-column [width]=100></e-column><e-column [width]=96></e-column><e-column [width]=120></e-column><e-column [width]=130></e-column><e-column [width]=120></e-column></e-columns></e-sheet></e-sheets></ejs-spreadsheet>"
})
export class AppComponent implements OnInit {
    public data?: object[];
    ngOnInit(): void {
        this.data = data;
    }
    beforeSave (args: BeforeSaveEventArgs) {
        args.pdfLayoutSettings!.orientation = 'Landscape'; // You can change the orientation of the PDF document
    }
 }
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));