From e940b59776fe5fc00bb0a3a0cc70090061ccb782 Mon Sep 17 00:00:00 2001 From: MOHANRAJSF4991 Date: Fri, 14 Aug 2026 12:47:00 +0530 Subject: [PATCH 1/4] 1029584: Added the open and save excel files --- .../open-excel-file/from-aws-s3-bucket.md | 176 ++++++ .../from-azure-blob-storage.md | 154 +++++ .../from-google-cloud-storage.md | 145 +++++ .../open-excel-file/from-google-drive.md | 188 ++++++ .../ASP-NET-CORE/open-excel-files.md | 576 ++++++++++++++++++ .../save-excel-file/to-aws-s3-bucket.md | 159 +++++ .../save-excel-file/to-azure-blob-storage.md | 126 ++++ .../to-google-cloud-storage.md | 114 ++++ .../save-excel-file/to-google-drive.md | 200 ++++++ .../ASP-NET-CORE/save-excel-files.md | 484 +++++++++++++++ 10 files changed, 2322 insertions(+) create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-files.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-aws-s3-bucket.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-azure-blob-storage.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-cloud-storage.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-drive.md create mode 100644 Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-files.md diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md new file mode 100644 index 0000000000..62eac0fcc3 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md @@ -0,0 +1,176 @@ +--- +layout: post +title: Open Excel from AWS S3 in React Spreadsheet Control | Syncfusion +description: How to open an Excel file from AWS S3 in the React Spreadsheet control of Syncfusion Essential JS 2 and more details. +platform: document-processing +control: Open file from AWS S3 +documentation: ug +--- + +# Open file from AWS S3 + +To load a file from AWS S3 in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +2. Open the `SpreadsheetController.cs` file in your web service project. + +3. Import the required namespaces at the top of the file: + +```csharp + +using Amazon; +using Amazon.Runtime; +using Amazon.S3; +using Amazon.S3.Model; +using Amazon.S3.Transfer; + +``` + +4. Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```csharp + +private IConfiguration _configuration; +public readonly string _accessKey; +public readonly string _secretKey; +public readonly string _bucketName; + +public SpreadsheetController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration) +{ + _hostingEnvironment = hostingEnvironment; + _cache = cache; + _configuration = configuration; + _accessKey = _configuration.GetValue("AccessKey"); + _secretKey = _configuration.GetValue("SecretKey"); + _bucketName = _configuration.GetValue("BucketName"); +} + +``` + +5. Create the `OpenFromS3()` method to open the document from the AWS S3 bucket. + +```csharp + +[Route("api/[controller]")] +[ApiController] +public class SpreadsheetController : ControllerBase +{ + [HttpPost] + [Route("OpenFromS3")] + public async Task OpenFromS3([FromBody] FileOptions options) + { + try + { + //Set AWS region and credentials + var region = RegionEndpoint.USEast1; + var config = new AmazonS3Config { RegionEndpoint = region }; + var credentials = new BasicAWSCredentials("your-access-key", "your-secretkey"); + //Create an S3 client to interact with AWS + using (var client = new AmazonS3Client(credentials, config)) + { + using (MemoryStream stream = new MemoryStream()) + { + //Get the full file name using input from the client + string bucketName = "your-bucket-name"; + string fileName = options.FileName + options.Extension; + //Download the file from S3 into memory + var response = await client.GetObjectAsync(new GetObjectRequest + { + BucketName = bucketName, + Key = fileName + }); + await response.ResponseStream.CopyToAsync(stream); + stream.Position = 0; // Reset stream position for reading + //Wrap the stream as a FormFile for processing + OpenRequest open = new OpenRequest + { + File = new FormFile(stream, 0, stream.Length, options.FileName, fileName) + }; + //Convert Excel file to JSON using Workbook.Open method. + var result = Workbook.Open(open); + //Return the JSON result to the client + return Content(result, "application/json"); + } + } + } + catch (Exception ex) + { + // Handle any errors and return a message + Console.WriteLine($"Error: {ex.Message}"); + return Content("Error occurred while processing the file."); + } + } + + // To receive file details from the client. + public class FileOptions + { + public string FileName { get; set; } = string.Empty; + public string Extension { get; set; } = string.Empty; + } +} + +``` + +6. Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration. + +```json + +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "AccessKey": "Your Access Key from AWS S3", + "SecretKey": "Your Secret Key from AWS S3", + "BucketName": "Your Bucket name from AWS S3" +} + +``` + +N> Replace **Your Access Key from AWS S3**, **Your Secret Key from AWS S3**, and **Your Bucket name from AWS S3** with your actual AWS access key, secret key and bucket name. + +**Step 3:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and load the Excel file from the AWS S3 bucket into the client-side spreadsheet. + +```ts + + + +// Function to open a spreadsheet file from AWS S3 via an API call +const openFromS3 = () => { + spreadsheet.showSpinner(); + // Make a POST request to the backend API to fetch the file from S3. Replace the URL with your local or hosted endpoint URL. + fetch('https://localhost:portNumber/api/spreadsheet/OpenFromS3', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + FileName: fileInfo.name, // Name of the file to open + Extension: fileInfo.extension, // File extension + }), + }) + .then((response) => response.json()) // Parse the response as JSON + .then((data) => { + spreadsheet.hideSpinner(); + // Load the spreadsheet data into the UI. + spreadsheet.openFromJson({ file: data, triggerEvent: true }); + }) + .catch((error) => { + // Log any errors that occur during the fetch operation + window.alert('Error importing file:', error); + }); +}; + +``` + +N> The **AWSSDK.S3** NuGet package must be installed in your application to use the previous code example. \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md new file mode 100644 index 0000000000..cb3ce3789f --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md @@ -0,0 +1,154 @@ +--- +layout: post +title: Open excel from Azure Blob in React Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from Azure Blob Storage in React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Open file from Azure Blob Storage +documentation: ug +--- + +# Open file from Azure Blob Storage + +To load a file from Azure Blob Storage in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +2. Open the `SpreadsheetController.cs` file in your web service project. + +3. Import the required namespaces at the top of the file: + +```csharp + +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Syncfusion.EJ2.Spreadsheet; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Specialized; + +``` + +4. Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```csharp + +private readonly string _storageConnectionString; +private readonly string _storageContainerName; + +public SpreadsheetController(IConfiguration configuration) +{ + // Fetch values from appsettings.json + _storageConnectionString = configuration.GetValue("connectionString"); + _storageContainerName = configuration.GetValue("containerName"); +} + +``` + +5. Create the `OpenFromAzure()` method to open the document from the Azure Blob Storage. + +```csharp + +[HttpPost] +[Route("OpenFromAzure")] +public async Task OpenFromAzure([FromBody] FileOptions options) +{ + if (options == null || string.IsNullOrWhiteSpace(options.FileName) || string.IsNullOrWhiteSpace(options.Extension)) + return BadRequest("Invalid file options."); + + try + { + using (MemoryStream stream = new MemoryStream()) + { + string fileName = options.FileName + options.Extension; + + // Connect to Azure Blob Storage + BlobServiceClient blobServiceClient = new BlobServiceClient(_storageConnectionString); + BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageContainerName); + BlockBlobClient blockBlobClient = containerClient.GetBlockBlobClient(fileName); + + // Download file into memory + await blockBlobClient.DownloadToAsync(stream); + stream.Position = 0; + + // Wrap stream as FormFile and convert to Spreadsheet-compatible JSON + OpenRequest open = new OpenRequest + { + File = new FormFile(stream, 0, stream.Length, options.FileName, fileName) + }; + + string result = Workbook.Open(open); + return Content(result, "application/json"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + return Content("Error occurred while processing the file."); + } +} + +// DTO that receives file details from the client +public class FileOptions +{ + public string FileName { get; set; } = string.Empty; + public string Extension { get; set; } = string.Empty; +} + +``` + +6. Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration. + +```json + +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "connectionString": "DefaultEndpointsProtocol=https;AccountName=yourAccount;AccountKey=yourKey;EndpointSuffix=core.windows.net", + "containerName": "your-container-name" +} + +``` +N> Note: Install the Azure.Storage.Blobs NuGet package in the service project. + +**Step 3:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and load the Excel file from the Google Cloud Storage into the client-side spreadsheet. + +```ts + +; + +const openFromAzure = () => { + spreadsheet.showSpinner(); + + fetch("https://localhost:portNumber/api/spreadsheet/OpenFromAzure", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + FileName: fileInfo.name, // e.g., "Report" + Extension: fileInfo.extension // e.g., ".xlsx" + }) + }) + .then((res) => res.json()) + .then((data) => { + spreadsheet.hideSpinner(); + spreadsheet.openFromJson({ file: data, triggerEvent: true }); + }) + .catch((err) => window.alert("Error importing file: " + err)); +}; + +``` \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md new file mode 100644 index 0000000000..d691482fe4 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md @@ -0,0 +1,145 @@ +--- +layout: post +title: Open excel from Google Cloud in React Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from Google Cloud Storage in React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Open file from Google Cloud Storage +documentation: ug +--- + +# Open file from Google Cloud Storage + +To load a file from Google Cloud Storage in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +2. Open the `SpreadsheetController.cs` file in your web service project. + +3. Import the required namespaces at the top of the file: + +```csharp + +using Google.Apis.Auth.OAuth2; +using Google.Cloud.Storage.V1; +using Syncfusion.EJ2.Spreadsheet; + +``` + +4. Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```Csharp + +private readonly string _bucketName; +private readonly StorageClient _storageClient; + +public SpreadsheetController(IConfiguration configuration) +{ + // Path of the JSON key downloaded from Google Cloud + string keyFilePath = configuration.GetValue("GoogleKeyFilePath"); + + // Create StorageClient with service-account credentials + var credentials = GoogleCredential.FromFile(keyFilePath); + _storageClient = StorageClient.Create(credentials); + + // Bucket that stores the Excel files + _bucketName = configuration.GetValue("BucketName"); +} + +``` + +5. Create the `OpenFromGoogleCloud()` method to open the document from the Google Cloud Storage. + +```Csharp + +[HttpPost] +[Route("OpenFromGoogleCloud")] +public IActionResult OpenFromGoogleCloud([FromBody] FileOptions options) +{ + try + { + using MemoryStream stream = new MemoryStream(); + + // / + string fileName = options.FileName + options.Extension; + + // Download the object into memory + _storageClient.DownloadObject(_bucketName, fileName, stream); + stream.Position = 0; + + // Feed the stream to Syncfusion to convert it into JSON + OpenRequest open = new OpenRequest + { + File = new FormFile(stream, 0, stream.Length, options.FileName, fileName) + }; + + string result = Workbook.Open(open); + return Content(result, "application/json"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + return Content("Error occurred while processing the file."); + } +} + +// DTO that receives file details from the client +public class FileOptions +{ + public string FileName { get; set; } = string.Empty; + public string Extension { get; set; } = string.Empty; +} + +``` + +6. Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration. + +```Json + +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "GoogleKeyFilePath": "path/to/service-account-key.json", + "BucketName": "your-gcs-bucket-name" +} + +``` + +N> Note: Install the Google.Cloud.Storage.V1 NuGet package in the service project. + +**Step 3:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and load the Excel file from the Google Cloud Storage into the client-side spreadsheet. + +```typescript +; + +const openFromGoogleCloud = () => { + spreadsheet.showSpinner(); + + fetch("https://localhost:portNumber/api/spreadsheet/OpenFromGoogleCloud", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + FileName: fileInfo.name, // e.g., "Report" + Extension: fileInfo.extension, // e.g., ".xlsx" + }), + }) + .then((res) => res.json()) + .then((data) => { + spreadsheet.hideSpinner(); + spreadsheet.openFromJson({ file: data, triggerEvent: true }); + }) + .catch((err) => window.alert("Error importing file: " + err)); +}; +``` \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md new file mode 100644 index 0000000000..e387f50fb1 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md @@ -0,0 +1,188 @@ +--- +layout: post +title: Open excel from Google Drive in React Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from Google Drive in React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Open file from Google Drive +documentation: ug +--- + +# Open file from Google Drive + +To load a file from Google Drive in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Set up Google Drive API + +You must set up a project in the Google Developers Console and enable the Google Drive API. Obtain the necessary credentials to access the API. For more information, view the official [link](https://developers.google.com/workspace/drive/api/guides/enable-sdk). + +**Step 2:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 3:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +* Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +* Open the `SpreadsheetController.cs` file in your web service project. + +* Import the required namespaces at the top of the file: + +```csharp + +using Google.Apis.Auth.OAuth2; +using Google.Apis.Drive.v3; +using Google.Apis.Services; +using Syncfusion.EJ2.Spreadsheet; + +``` + +* Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```csharp + +//variables for storing GDrive folderId, ApplicationName and Service-Accountkey credentials +public readonly string folderId; +public readonly string applicationName; +public readonly string credentialPath; + +//constructor for assigning credentials +public SpreadsheetController(IConfiguration configuration) +{ + folderId = configuration.GetValue("FolderId"); + credentialPath = configuration.GetValue("CredentialPath"); + applicationName = configuration.GetValue("ApplicationName"); +} + +``` + +* Create the `OpenExcelFromGoogleDrive()` method to open the document from the Google Drive. + +```csharp + +[HttpPost] +[Route("OpenExcelFromGoogleDrive")] +public async Task OpenExcelFromGoogleDrive([FromBody] FileOptions options) +{ +try +{ + // Create a memory stream to store file data + MemoryStream stream = new MemoryStream(); + + // Authenticate using Service Account + GoogleCredential credential; + // Load Google service account credentials + using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read)) + { + credential = GoogleCredential.FromStream(streamKey) + .CreateScoped(DriveService.Scope.Drive); + } + + // Create Google Drive API service + var service = new DriveService(new BaseClientService.Initializer() + // Initialize Google Drive API client + { + HttpClientInitializer = credential, + ApplicationName = applicationName, + }); + + // List Excel files in Google Drive folder + var listRequest = service.Files.List(); + // Query Google Drive for Excel, CSV files in the specified folder + listRequest.Q = $"(mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' or mimeType='application/vnd.ms-excel' or mimeType='text/csv') and '{folderId}' in parents and trashed=false"; + listRequest.Fields = "files(id, name)"; + var files = await listRequest.ExecuteAsync(); + // Find the requested file + string fileIdToDownload = files.Files.FirstOrDefault(f => f.Name == options.FileName + options.Extension)?.Id; + // Get the file ID for the requested file name + if (string.IsNullOrEmpty(fileIdToDownload)) + // Get the file ID for the requested file name + return NotFound("File not found in Google Drive."); + // Download the file + var request = service.Files.Get(fileIdToDownload); + await request.DownloadAsync(stream); + // Download file content into memory stream + stream.Position = 0; + // Prepare file for Syncfusion Excel processing + OpenRequest open = new OpenRequest + // Wrap downloaded stream as FormFile for Syncfusion processing + { + File = new FormFile(stream, 0, stream.Length, options.FileName, options.FileName + options.Extension) + }; + + // Convert Excel file to JSON using Syncfusion XlsIO + var result = Workbook.Open(open); + return Content(result, "application/json"); +} +catch (Exception ex) +{ + return BadRequest("Error occurred while processing the file: " + ex.Message); +} +} + +// Class to store FileOptions +public class FileOptions +{ + public string FileName { get; set; } = string.Empty; + public string Extension { get; set; } = string.Empty; +} + +``` + +* Open the `appsettings.json` file in your web service project, add your Google Drive configuration details. + +```json + +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CredentialPath": "path-to-your-service-account-key.json", + "FolderId": "your-google-drive-folder-id", + "ApplicationName": "YourAppName" +} + +``` + +N> Replace the **credential path**, **folderId** and **application name** in json file with your actual Google drive folder ID , your name for your application and the path for the JSON file. + +**Step 4:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and process the Excel file from the Google Drive and load the JSON result into the client-side spreadsheet using the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method. + +```typescript + + +const openFromGoogleDrive = () => { + spreadsheet.showSpinner(); + // Make a POST request to the backend API to open the file from Google Drive. + // Replace the URL with your local or hosted endpoint URL. + fetch('https://localhost:your_port_number/api/spreadsheet/OpenExcelFromGoogleDrive', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + FileName: fileInfo.name, // Name of the file to open + Extension: fileInfo.extension, // File extension (.xlsx) + }), + }) + .then((response) => response.json()) // Parse the response as JSON + .then((data) => { + spreadsheet.hideSpinner(); + // Load the spreadsheet data into the UI + spreadsheet.openFromJson({ file: data, triggerEvent: true }); + }) + .catch((error) => { + spreadsheet.hideSpinner(); + window.alert('Error importing file from Google Drive: ' + error); + }); +}; +``` + +N> The Google.Apis.Drive.v3 NuGet package must be installed in your application to use the previous code example. + +[View sample in GitHub](https://github.com/SyncfusionExamples/syncfusion-react-spreadsheet-google-drive-integration) diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-files.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-files.md new file mode 100644 index 0000000000..c7ea849e09 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-files.md @@ -0,0 +1,576 @@ +--- +layout: post +title: Open Excel in React Spreadsheet component | Syncfusion +description: Learn here all about Open Excel in Syncfusion React Spreadsheet component of Syncfusion Essential JS 2 and more. +platform: document-processing +control: Open +documentation: ug +--- + +# Open Excel Files in React Spreadsheet + +The [React Spreadsheet Editor](https://www.syncfusion.com/spreadsheet-editor-sdk/react-spreadsheet-editor) component uses a server-assisted workflow to open Excel files efficiently and accurately. When a user uploads an Excel file, the file is sent to a server endpoint for processing. This keeps the browser fast and responsive, as all heavy parsing and conversion are handled on the server. + +On the server, the [`Syncfusion.EJ2.Spreadsheet`](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core) library is used to process the uploaded Excel file. This library is built on top of [`Syncfusion XlsIO`](https://help.syncfusion.com/document-processing/excel/excel-library/net/overview), which itself is implemented using **.NET Frameworks**. The server extracts all data, styles, formulas, formatting, and sheet structure, then converts everything into a Spreadsheet-compatible JSON format. This JSON is sent back to the client, where the React Spreadsheet component renders the workbook in the browser, preserving the original Excel layout and content. + +In the code samples and demos, you may see **Syncfusion-hosted service URLs** used for the `openUrl` and `saveUrl` properties. These URLs point to Syncfusion’s own WebAPI services (built with **ASP.NET Core**) that handle opening and 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 open/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 `Open` endpoint using ASP.NET Core WebAPI, which is the same approach used for building the hosted Syncfusion URLs. This endpoint receives the uploaded Excel file, processes it with the Syncfusion Spreadsheet library, and returns the workbook JSON to the client: + +```csharp +// Open action +[HttpPost] +[Route("Open")] +public IActionResult Open([FromForm] IFormCollection openRequest) +{ + OpenRequest open = new OpenRequest(); + if (openRequest.Files && openRequest.Files.Count > 0) { + open.File = openRequest.Files[0]; + return Content(Workbook.Open(open)); + } + return BadRequest("No file uploaded."); +} +``` + +> **Note:** For details on how to set up your own web service for open/save operations, refer to the [web service](./web-services/webservice-overview) 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](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core)
[Syncfusion.EJ2.AspNet.Core](https://www.nuget.org/packages/Syncfusion.EJ2.AspNet.Core)
[Syncfusion.XlsIORenderer.Net.Core](https://www.nuget.org/packages/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](https://www.nuget.org/packages/Syncfusion.XlsIO.AspNet.Mvc5)
[Syncfusion.ExcelToPdfConverter.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.ExcelToPdfConverter.AspNet.Mvc5)
[Syncfusion.Pdf.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.Pdf.AspNet.Mvc5/)
[Syncfusion.ExcelChartToImageConverter.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.ExcelChartToImageConverter.AspNet.Mvc5)
[Syncfusion.EJ2.MVC5](https://www.nuget.org/packages/Syncfusion.EJ2.MVC5) | + +For more details, see the [dependencies section on nuget.org](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core#dependencies-body-tab). + +To enable opening Excel files, set the [`allowOpen`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowopen) property to **true** and specify the service url using the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property. The control will send the uploaded file to this endpoint, where it is processed and returned as JSON for the Spreadsheet to render. + +For a quick walkthrough on how the open functionality works, refer to the following video: +{% youtube "https://www.youtube.com/watch?v=MpwiXmL1Z_o" %} + +## UI options to open Excel files + +In the user interface you can open an Excel document by clicking `File > Open` menu item in ribbon. + +The following sample shows the `Open` option configured by using the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property. You can also use the [`beforeOpen`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforeopen) event to customize or cancel the import action, which is triggered before opening an Excel file. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs1/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs1/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs1" %} + +Please find the below table for the [beforeOpen](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforeopen) event arguments. + +**BeforeOpenEventArgs – Properties** + +| **Property** | **Type** | **Description** | +|-------------------|-------------------------------|-------------| +| **cancel** | `boolean` | Specifies whether the open action should be canceled. | +| **file** | `FileList` \| `string` \| `File` | Specifies the file to be opened. | +| **parseOptions** | [`WorkbookParseOptions`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/workbookparseoptions) | Specifies the parsing options that control how the Excel file is interpreted during loading. | +| **password** | `string` | Specifies the password required to open the Excel file, if it is protected. | +| **requestData** | object | Specifies any additional data sent along with the open request. | +| **requestType** | `string` | Specifies the type of open request that triggered the **beforeOpen** event. Possible values:

• **initial** – The default request made when loading a workbook.
• **chunk** – A follow‑up request to load a portion of the workbook when chunking is enabled and the server provides a chunk plan.
• **thresholdLimitConfirmed** – A request made after the user confirms a threshold warning (such as *maximumDataLimit* or *maximumFileSizeLimit*) and chooses to proceed. | + +> * Use `Ctrl + O` keyboard shortcut to open Excel documents. +> * The default value of the [allowOpen](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowopen) property is `true`. For demonstration purpose, we have showcased the [allowOpen](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowopen) property in previous code snippet. + +## Open Excel files programmatically + +To open Excel files programmatically in the Spreadsheet, you can use the [`open`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#open) method of the Spreadsheet component. Before invoking this method, ensure that the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property is properly configured, as it is required for processing the file on the server. + +Please find the table below for the [`open`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#open) method arguments. + +| **Parameter** | **Type** | **Description** | +|----------|--------------|-----------------------------------| +| options | [OpenOptions](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/openOptions) | Options for opening the excel file. | + + +The following code example demonstrates how to open an Excel file programmatically in the Spreadsheet. + +```js +import React, { useRef } from 'react'; +import { createRoot } from 'react-dom/client'; +import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet'; + +const App = () => { + const spreadsheetRef = useRef(null); + + const onCreated = () => { + fetch('https://js.syncfusion.com/demos/ejservices/data/Spreadsheet/LargeData.xlsx') + .then((response) => response.blob()) + .then((fileBlob) => { + const file = new File([fileBlob], 'Sample.xlsx'); + spreadsheetRef.current?.open({ file }); + }); + }; + + return ( + + ); +}; + +export default App; + +const root = createRoot(document.getElementById('spreadsheet')); +root.render(); +``` + +## Supported Excel file formats for Open + +The following Excel file formats are supported for opening in the Spreadsheet component: + +* Microsoft Excel Workbook (.xlsx) +* Microsoft Excel 97–2003 Workbook (.xls) +* Comma-Separated Values (.csv) +* Excel Macro‑Enabled Workbook (.xlsm) +* Excel Binary Workbook (.xlsb) + +## Import options + +### Open Excel files from local system + +If you explore your machine to select and upload an Excel document using the file upload component, you will receive the uploaded document as a raw file in the [success](https://ej2.syncfusion.com/react/documentation/api/uploader/index-default#success) event of the file upload component. In this `success` event, you should pass the received raw file as an argument to the Spreadsheet's [open](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#open) method to see the appropriate output. + +The following code example shows how to import an Excel document using file upload component in spreadsheet. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs9/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs9/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs9" %} + +### Open Excel files from URL + +You can achieve to access the remote Excel file by using the [`created`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#created) event. In this event you can fetch the Excel file and convert it to a blob. Convert this blob to a file and [`open`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#open) this file by using Spreadsheet component open method. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs2/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs2/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs2" %} + +### Open Excel files from Blob Data + +By default, the Spreadsheet component provides an option to browse files from the local file system and open them within the component. If you want to open an Excel file from blob data, you need to fetch the blob data from the server or another source and convert this blob data into a `File` object. Then, you can use the [open](https://ej2.syncfusion.com/react/documentation/api/spreadsheet#open) method in the Spreadsheet component to load that `File` object. + +Please find the code to fetch the blob data and load it into the Spreadsheet component below. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-from-blobdata-cs1/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-from-blobdata-cs1/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-from-blobdata-cs1" %} + +### Load Workbook as JSON + +The Spreadsheet component allows you to load an entire workbook using a JSON object. This JSON is typically generated by the Spreadsheet server by converting an Excel file into a Spreadsheet‑compatible workbook JSON, but it can also be created manually. When loaded, the component reads the JSON and restores all workbook details, including sheets, cells, styles, formulas, formatting, and other associated metadata. + +You can optionally pass deserialization options to the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method to ignore specific features when loading the JSON. For example, you can exclude styles, formulas, number formats, images, or conditional formatting. These options are optional—if you do not specify them, the method restores the full workbook details by default. + +Reference: Guide to Creating the JSON Structure: https://help.syncfusion.com/document-processing/excel/spreadsheet/react/how-to/create-a-object-structure. + +The following example demonstrates how to load a workbook JSON into the Spreadsheet component. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-from-json-cs1/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-from-json-cs1/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-from-json-cs1" %} + +### Load server-side Excel files into Spreadsheet + +By default, the Spreadsheet component provides an option to browse files from the local file system and open them within the component. If you want to load an Excel file located on a server, you need to configure the server endpoint to fetch the Excel file from the server location, process it using `Syncfusion.EJ2.Spreadsheet.AspNet.Core`, and send it back to the client side as `JSON data`. On the client side, you should use the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method to load that `JSON data` into the Spreadsheet component. + +**Server Endpoint**: + +```csharp + public IActionResult Open([FromBody] FileOptions options) + { + OpenRequest open = new OpenRequest(); + string filePath = _env.ContentRootPath.ToString() + "\\Files\\" + options.FileName + ".xlsx"; + // Getting the file stream from the file path. + FileStream fileStream = new FileStream(filePath, FileMode.Open); + // Converting "MemoryStream" to "IFormFile". + IFormFile formFile = new FormFile(fileStream, 0, fileStream.Length, "", options.FileName + ".xlsx"); + open.File = formFile; + // Processing the Excel file and return the workbook JSON. + var result = Workbook.Open(open); + fileStream.Close(); + return Content(result); + } + + public class FileOptions + { + public string FileName { get; set; } = string.Empty; + } +``` + +**Client Side**: + +```js + + // Fetch call to server to load the Excel file. + fetch('https://localhost:{{Your_port_number}}/Home/Open', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ FileName: 'Sample' }), + }) + .then((response) => response.json()) + .then((data) => { + // Load the JSON data into spreadsheet. + spreadsheet.openFromJson({ file: data }); + }) + +``` + +You can find the server endpoint code to fetch and process the Excel file in this [attachment](https://www.syncfusion.com/downloads/support/directtrac/general/ze/WebApplication1_(1)-880363187). After launching the server endpoint, you need to update the URL on the client side sample as shown below. + +```js +// To open an Excel file from the server. +fetch('https://localhost:{{port_number}}/Home/Open') +``` + +### Open Excel files with AWS Lambda + +Before proceeding with the opening 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](https://support.syncfusion.com/kb/article/17184/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 opening the Excel file with this hosted open URL, you need to prevent the default file opening process to avoid getting a corrupted file on the open service end. The spreadsheet component appends the file to the `formData` and sends it to the open service, which causes the file to get corrupted. To prevent this, set the `args.cancel` value to `true` in the [`beforeOpen`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforeopen) event. After that, you will get the selected file in the `beforeOpen` event argument. Then, convert this file into a base64 string and send it to the open service URL using a fetch request. + +On the open service end, convert the base64 string back to a file and pass it as an argument to the workbook `Open` method. The open service will process the file and return the spreadsheet data in JSON format. You will then receive this JSON data in the fetch success callback. Finally, use the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method to load this JSON data into the spreadsheet component. + +The following code example shows how to open an Excel file using a hosted web service in AWS Lambda, as mentioned above. + +```js +function Default() { + let spreadsheet; + const beforeOpenHandler = (eventArgs) => { + eventArgs.cancel = true; // To prevent the default open action. + if (eventArgs.file) { + const reader = new FileReader(); + reader.readAsDataURL(eventArgs.file); + reader.onload = () => { + // Removing the xlsx file content-type. + const base64Data = reader.result.replace('data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,', ''); + openExcel({ + file: base64Data, + extension: eventArgs.file.name.slice(eventArgs.file.name.lastIndexOf('.') + 1), + password: eventArgs.password || '' + }); + }; + } + }; + const openExcel = (requestData) => { + // Fetch call to AWS server for open processing. + fetch('https://xxxxxxxxxxxxxxxxxx.amazonaws.com/Prod/api/spreadsheet/open', { + method: 'POST', + headers: { + 'Accept': 'application/json, text/plain', + 'Content-Type': 'application/json;charset=UTF-8' + }, + body: JSON.stringify(requestData) + }).then((response) => { + if (response.ok) { + return response.json(); + } + }).then((data) => { + // Loading the JSON data into our spreadsheet. + if (data.Workbook && data.Workbook.sheets) { + spreadsheet.openFromJson({ file: data }); + } + }).catch((error) => { + console.log(error); + }); + }; + return (
+
+ { spreadsheet = ssObj; }} beforeOpen={beforeOpenHandler}> + +
+
); +} +export default Default; +``` + +```csharp +public IActionResult Open(OpenOptions openOptions) +{ + // Convert the base64 string to bytes array. + byte[] bytes = Convert.FromBase64String(openOptions.File); + // Loading the bytes array to stream. + MemoryStream stream = new MemoryStream(bytes); + OpenRequest open = new OpenRequest(); + // Converting the stream into FormFile. + open.File = new FormFile(stream, 0, bytes.Length, "Sample", "Sample." + openOptions.Extension); + if (string.IsNullOrEmpty(openOptions.Password)) + open.Password = openOptions.Password; + var result = Workbook.Open(open); + return Content(result); +} + +public class OpenOptions +{ + public string File { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public string Extension { get; set; } = string.Empty; +} +``` + +### Open Base64-encoded Excel data + +In the Spreadsheet, there is no direct option to open data as a `Base64` string. To achieve this, the `import()` function fetches the `Base64` string, converts it to a Blob, creates a File object from the Blob, and then opens it using the [open](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#open) method in the spreadsheet. + +The following code example shows how to open the spreadsheet data as base64 string. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/base-64-string/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/base-64-string/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/base-64-string" %} + + +### Open Excel files in read-only mode + +You can open Excel file into a read-only mode by using the [`openComplete`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#opencomplete) event. In this event, you must protect all the sheets and lock its used range cells by using [`protectSheet`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#protectsheet) and [`lockCells`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#lockcells) methods. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs4/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs4/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs4" %} + + +## Advanced Open Options + +### Configure JSON Deserialization + +Previously, when opening a workbook JSON object into the Spreadsheet using the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method, the entire workbook, including all features specified in the JSON object, was processed and loaded into the Spreadsheet. + +Now, you have the option to selectively ignore some features during the opening of the JSON object by configuring deserialization options and passing them as arguments to the `openFromJson` method. This argument is optional, and if not configured, the entire workbook JSON object will be loaded without ignoring any features. + +```ts +spreadsheet.openFromJson({ file: file }, { ignoreStyle: true }); +``` + +| Option | Description | +| ------ | ----------- | +| onlyValues | If **true**, only cell values are loaded. | +| ignoreStyle | If **true**, styles are excluded when loading the JSON data. | +| ignoreFormula | If **true**, formulas are excluded when loading the JSON data. | +| ignoreFormat | If **true**, number formats are excluded when loading the JSON data. | +| ignoreConditionalFormat | If **true**, conditional formatting is excluded when loading the JSON data. | +| ignoreValidation | If **true**, data validation rules are excluded when loading the JSON data. | +| ignoreFreezePane | If **true**, freeze panes are excluded when loading the JSON data. | +| ignoreWrap | If **true**, text wrapping settings are excluded when loading the JSON data. | +| ignoreChart | If **true**, charts are excluded when loading the JSON data. | +| ignoreImage | If **true**, images are excluded when loading the JSON data. | +| ignoreNote | If **true**, notes are excluded when loading the JSON data. | + +The following code snippet demonstrates how to configure the deserialization options and pass them as arguments to the `openFromJson` method: + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-from-json/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-from-json/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-from-json" %} + +### Optimize Open Performance with Parsing Options + +Opening large Excel files into the React Spreadsheet can sometimes lead to slower performance and increased memory usage. This is often caused by the processing of additional elements such as styles and number formats—even when the actual data content is minimal. For example, an Excel file with only a small amount of data but a large number of styled or formatted empty cells can significantly impact load time and memory consumption. + +To address this, we've introduced parsing options that allow users to selectively skip non-essential features during the open process. By enabling options like `IgnoreStyle` and `IgnoreFormat`, you can reduce the amount of data processed, resulting in: +* Faster load times +* Lower memory usage +* Smaller JSON responses + +These enhancements are especially beneficial for users working with large or complex Excel files, offering a more efficient and responsive experience. + +> **Note:** These options are ideal when styles and number formats are not critical to your use case and the focus is on loading the actual data efficiently. + +The code example below demonstrates how to configure the `IgnoreStyle` and `IgnoreFormat` parsing options on the `server-side`. + +**Code Snippet:** + +**Server-Side Configuration:** +```csharp +public IActionResult Open(IFormCollection openRequest) +{ + OpenRequest open = new OpenRequest(); + ... + open.ParseOptions = new WorkbookParseOptions() { + IgnoreStyle = true, + IgnoreFormat = true + }; + ... + return Content(Workbook.Open(open)); +} +``` + +### Open Large Excel Files with Chunk Response Processing + +When opening large Excel files with many features and data, the server response can become very large. This might cause memory issues or connection problems during data transmission. The `Chunk Response Processing` feature solves this by dividing the server response into smaller parts, called chunks, and sending them to the client in parallel. The client receives these chunks and combines them to load the Excel data smoothly into the spreadsheet. + +You can enable this feature by setting the [`chunkSize`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/opensettings#chunksize) property in the [`openSettings`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#opensettings) object. Set the [`chunkSize`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/opensettings#chunksize) to a value greater than 0 (in bytes). The [`chunkSize`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/opensettings#chunksize) defines how large each chunk will be. Make sure your server supports chunked responses to use this feature effectively. + +> This feature reduces memory usage on both the server and client, ensuring that resources are managed efficiently during data transmission. By sending smaller parts of data, it prevents connection issues that could occur with large payloads, making the transmission process more reliable. Additionally, it allows large Excel files to be loaded smoothly into the spreadsheet, providing a seamless user experience even with extensive data. + +The following code example demonstrates the client-side and server-side configuration required for handling chunk-based responses when opening an Excel file. + +**Client Side**: + +```js +import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet'; + +const App = () => { + + const spreadsheetRef = React.useRef(null); + const openSettings = { + // Specifies the size (in bytes) of each chunk for the server response when opening a document. + chunkSize: 1000000, + // Specifies the number of retry attempts for a failed server request when returning the opened file responses in chunks. + // This ensures reliable handling of temporary network or server disruptions during the chunked response process. + retryCount: 3, + // Specifies the delay (in milliseconds) before retrying a failed server request when returning the opened file responses in chunks. + // This ensures controlled retries in case of temporary network or server disruptions during the chunked response process. + retryAfterDelay: 500 + } + + const openUrl = 'https://localhost:{{port_number}}/Home/Open'; + + return ( +
+ + +
+ ); +} + +export default App; +``` + +**Server Endpoint**: + +```csharp +public IActionResult Open(IFormCollection openRequest) +{ + OpenRequest open = new OpenRequest(); + if (openRequest.Files.Count > 0) + { + open.File = openRequest.Files[0]; + } + Microsoft.Extensions.Primitives.StringValues chunkPayload; + if (openRequest.TryGetValue("chunkPayload", out chunkPayload)) + { + // The chunk payload JSON data includes information essential for processing chunked responses. + open.ChunkPayload = chunkPayload; + } + var result = Workbook.Open(open, 150); + return Content(result); +} +``` + +The [attachment](https://www.syncfusion.com/downloads/support/directtrac/general/ze/WebApplication1_7-101537213) includes the server endpoint code for handling chunk-based open processing. After launching the server endpoint, update the `openUrl` property of the spreadsheet in the client-side sample with the server URL, as shown below. + +```js + // Specifies the service URL for processing the Excel file, converting it into a format suitable for loading in the spreadsheet. + + +``` + +## Customization + +### Add custom headers to Open requests + +You can add your own custom header to the open action in the Spreadsheet. For processing the data, it has to be sent from server to client side and adding customer header can provide privacy to the data with the help of Authorization Token. Through the [`beforeOpen`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforeopen) event, the custom header can be added to the request during open action. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs3/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs3/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs3" %} + +### Handle External workbook reference confirmation + +When you open an Excel file that contains external workbook references, you will see a confirmation dialog. This dialog allows you to either continue with the file opening or cancel the operation. This confirmation dialog will appear only if you set the `AllowExternalWorkbook` property value to **false** during the open request, as shown below. This prevents the spreadsheet from displaying inconsistent data. + +```csharp +public IActionResult Open(IFormCollection openRequest) + { + OpenRequest open = new OpenRequest(); + open.AllowExternalWorkbook = false; + open.File = openRequest.Files[0]; + open.Guid = openRequest["Guid"]; + return Content(Workbook.Open(open)); + } +``` + +> This feature is only applicable when importing an Excel file and not when loading JSON data or binding cell data. + +![External workbook confirmation dialog](./images/external-reference-dialog-alert.png) \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-aws-s3-bucket.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-aws-s3-bucket.md new file mode 100644 index 0000000000..aca7617f1f --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-aws-s3-bucket.md @@ -0,0 +1,159 @@ +--- +layout: post +title: Saving Excel to AWS S3 in React Spreadsheet control | Syncfusion +description: Learn how to save an Excel file to AWS S3 in the React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Save file to AWS S3 +documentation: ug +--- + +# Save spreadsheet to AWS S3 + +To save a file to the AWS S3, you can follow the steps below. + +**Step 1:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +2. Open the `SpreadsheetController.cs` file in your web service project. + +3. Import the required namespaces at the top of the file: + +```csharp + +using Amazon; +using Amazon.Runtime; +using Amazon.S3; +using Amazon.S3.Model; +using Amazon.S3.Transfer; + +``` + +4. Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields + +```csharp + +private IConfiguration _configuration; +public readonly string _accessKey; +public readonly string _secretKey; +public readonly string _bucketName; + +public SpreadsheetController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration) +{ + _hostingEnvironment = hostingEnvironment; + _cache = cache; + _configuration = configuration; + _accessKey = _configuration.GetValue("AccessKey"); + _secretKey = _configuration.GetValue("SecretKey"); + _bucketName = _configuration.GetValue("BucketName"); +} + +``` + +5. Create the `SaveToS3()` method to open the document from the AWS S3 bucket + +```csharp + +[HttpPost] +[Route("SaveToS3")] +public async Task SaveToS3([FromForm] SaveSettings saveSettings) +{ + try + { + // Convert spreadsheet JSON to Excel file stream + Stream fileStream = Workbook.Save(saveSettings); + fileStream.Position = 0; // Reset stream for upload + + // Set AWS region and credentials + var region = RegionEndpoint.USEast1; + var config = new AmazonS3Config { RegionEndpoint = region }; + var credentials = new BasicAWSCredentials("your-access-key", "your-secretkey"); + + // Define S3 bucket and file name + string bucketName = "your-bucket-name"; + string fileName = saveSettings.FileName + "." + saveSettings.SaveType.ToString().ToLower(); + + // Initialize S3 client + using (var client = new AmazonS3Client(credentials, config)) + { + // Use TransferUtility to upload the file stream + var fileTransferUtility = new TransferUtility(client); + await fileTransferUtility.UploadAsync(fileStream, bucketName, fileName); + } + + // Return success message + return Ok("Excel file successfully saved to AWS S3."); + } + catch (Exception ex) + { + } +} + +``` + +6. Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration + +```json + +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "AccessKey": "Your Access Key from AWS S3", + "SecretKey": "Your Secret Key from AWS S3", + "BucketName": "Your Bucket name from AWS S3" +} + +``` + +N> Replace **Your Access Key from AWS S3**, **Your Secret Key from AWS S3**, and **Your Bucket name from AWS S3** with your actual AWS access key, secret key and bucket name + +**Step 3:** Modify the index File in the Spreadsheet sample to using [`saveAsJson`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveasjson) method to serialize the spreadsheet and send it to the back-end + +```js +// Function to save the current spreadsheet to AWS S3 via an API call +const saveToS3 = () => { + // Convert the current spreadsheet to JSON format + spreadsheet.saveAsJson().then((json) => { + const formData = new FormData(); + + // Append necessary data to the form for the API request + formData.append('FileName', loadedFileInfo.fileName); // Name of the file to save + formData.append('saveType', loadedFileInfo.saveType); // Save type + formData.append('JSONData', JSON.stringify(json.jsonObject.Workbook)); // Spreadsheet data + formData.append( + 'PdfLayoutSettings', + JSON.stringify({ FitSheetOnOnePage: false }) // PDF layout settings + ); + + // Make a POST request to the backend API to save the file to S3. Replace the URL with your local or hosted endpoint URL. + fetch('https://localhost:portNumber/api/spreadsheet/SaveToS3', { + method: 'POST', + body: formData, + }) + .then((response) => { + // Check if the response is successful + if (!response.ok) { + throw new Error( + `Save request failed with status ${response.status}` + ); + } + window.alert('Workbook saved successfully.'); + }) + .catch((error) => { + // Log any errors that occur during the save operation + window.alert('Error saving to server:', error); + }); + }); +}; +``` + +N> The **AWSSDK.S3** NuGet package must be installed in your application to use the previous code example. diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-azure-blob-storage.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-azure-blob-storage.md new file mode 100644 index 0000000000..f27c3bfc72 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-azure-blob-storage.md @@ -0,0 +1,126 @@ +--- +layout: post +title: Save excel to Azure Blob in React Spreadsheet control | Syncfusion +description: Learn about how to Save an Excel file from Azure Blob Storage in React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Save file to Azure Blob Storage +documentation: ug +--- + +# Save file to Azure Cloud Storage + +To save a file to Azure Blob Storage in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +2. Open the `SpreadsheetController.cs` file in your web service project. + +3. Import the required namespaces at the top of the file: + +```csharp + +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Syncfusion.EJ2.Spreadsheet; +using Azure.Storage.Blobs; + +``` + +4. Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```csharp + +private readonly string _storageConnectionString; +private readonly string _storageContainerName; + +public SpreadsheetController(IConfiguration configuration) +{ + _storageConnectionString = configuration.GetValue("connectionString"); + _storageContainerName = configuration.GetValue("containerName"); +} + +``` + +5. Create the `SaveToAzure()` method to save the document to the Azure Blob storage. + +```csharp + +[HttpPost] +[Route("SaveToAzure")] +public async Task SaveToAzure([FromForm] SaveSettings saveSettings) +{ + if (saveSettings == null || string.IsNullOrWhiteSpace(saveSettings.FileName)) + return BadRequest("Invalid save settings."); + + try + { + // Convert spreadsheet JSON to Excel/PDF/CSV stream + Stream fileStream = Workbook.Save(saveSettings); + fileStream.Position = 0; + + // Define Azure Blob Storage client + BlobServiceClient blobServiceClient = new BlobServiceClient(_storageConnectionString); + BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_storageContainerName); + + // Define blob name using file name and save type + string blobName = $"{saveSettings.FileName}.{saveSettings.SaveType.ToString().ToLower()}"; + BlobClient blobClient = containerClient.GetBlobClient(blobName); + + // Upload the Excel file stream to Azure Blob Storage (overwrite if exists) + await blobClient.UploadAsync(fileStream, overwrite: true); + + return Ok("Excel file successfully saved to Azure Blob Storage."); + } + catch (Exception ex) + { + return BadRequest("Error saving file to Azure Blob Storage: " + ex.Message); + } +} + +``` + +N> Note: Install the Azure.Storage.Blobs NuGet package in the service project. Ensure the configured connection string has permissions to read and write blobs in the specified container. + +**Step 3:** Modify the index File in the Spreadsheet sample to using [`saveAsJson`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveasjson) method to serialize the spreadsheet and send it to the back-end + +```js + +; + +const saveToAzure = () => { + spreadsheet.saveAsJson().then((json) => { + const formData = new FormData(); + formData.append("FileName", loadedFileInfo.fileName); // e.g., "Report" + formData.append("saveType", loadedFileInfo.saveType); // e.g., "Xlsx" + formData.append("JSONData", JSON.stringify(json.jsonObject.Workbook)); + formData.append( + "PdfLayoutSettings", + JSON.stringify({ FitSheetOnOnePage: false }) + ); + + fetch("https://localhost:portNumber/api/spreadsheet/SaveToAzure", { + method: "POST", + body: formData + }) + .then((res) => { + if (!res.ok) { + throw new Error(`Save failed with status ${res.status}`); + } + window.alert("Workbook saved successfully to Azure Blob Storage."); + }) + .catch((err) => window.alert("Error saving to server: " + err)); + }); +}; + +``` diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-cloud-storage.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-cloud-storage.md new file mode 100644 index 0000000000..d92d4dbf3a --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-cloud-storage.md @@ -0,0 +1,114 @@ +--- +layout: post +title: Save excel to Google Cloud in React Spreadsheet control | Syncfusion +description: Learn about how to Save an Excel file from Google Cloud Storage in React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Save file to Google Cloud Storage +documentation: ug +--- + +# Save file to Google Cloud Storage + +To save a file to Google Cloud Storage in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +2. Open the `SpreadsheetController.cs` file in your web service project. + +3. Import the required namespaces at the top of the file: + +```csharp + +using Google.Apis.Auth.OAuth2; +using Google.Cloud.Storage.V1; +using Syncfusion.EJ2.Spreadsheet; + +``` + +4. Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```csharp +private readonly string _bucketName; +private readonly StorageClient _storageClient; + +public SpreadsheetController(IConfiguration configuration) +{ + // Path of the JSON key downloaded from Google Cloud + string keyFilePath = configuration.GetValue("GoogleKeyFilePath"); + + // Create StorageClient with service-account credentials + var credentials = GoogleCredential.FromFile(keyFilePath); + _storageClient = StorageClient.Create(credentials); + + // Bucket that stores the Excel files + _bucketName = configuration.GetValue("BucketName"); +} +``` + +5. Create the `SaveToGoogleCloud()` method to save the document to the Google Cloud storage. + +```csharp +[HttpPost] +[Route("SaveToGoogleCloud")] +public async Task SaveToGoogleCloud([FromForm] SaveSettings saveSettings) +{ + try + { + // Convert spreadsheet JSON to Excel stream + Stream fileStream = Workbook.Save(saveSettings); + fileStream.Position = 0; + + // File name inside the bucket + string fileName = $"{saveSettings.FileName}.{saveSettings.SaveType.ToString().ToLower()}"; + + // Upload the stream to Google Cloud Storage + await _storageClient.UploadObjectAsync(_bucketName, fileName, null, fileStream); + + return Ok("Excel file successfully saved to Google Cloud Storage."); + } + catch (Exception ex) + { + return BadRequest("Error saving file to Google Cloud Storage: " + ex.Message); + } +} +``` + +**Step 3:** Modify the index File in the Spreadsheet sample to using [`saveAsJson`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveasjson) method to serialize the spreadsheet and send it to the back-end + +```js + +const saveToGoogleCloud = () => { + spreadsheet.saveAsJson().then(json => { + const formData = new FormData(); + formData.append('FileName', loadedFileInfo.fileName); // e.g., "Report" + formData.append('saveType', loadedFileInfo.saveType); // e.g., "Xlsx" + formData.append('JSONData', JSON.stringify(json.jsonObject.Workbook)); + formData.append( + 'PdfLayoutSettings', + JSON.stringify({ FitSheetOnOnePage: false }) + ); + + fetch('https://localhost:portNumber/api/spreadsheet/SaveToGoogleCloud', { + method: 'POST', + body: formData + }) + .then(res => { + if (!res.ok) { + throw new Error(`Save failed with status ${res.status}`); + } + window.alert('Workbook saved successfully to Google Cloud Storage.'); + }) + .catch(err => window.alert('Error saving to server: ' + err)); + }); +}; +``` + +N> Note: The back-end requires the Google.Cloud.Storage.V1 NuGet package and a service-account key that has Storage Object Admin (or equivalent) permissions on the target bucket. \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-drive.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-drive.md new file mode 100644 index 0000000000..0ececc1600 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-file/to-google-drive.md @@ -0,0 +1,200 @@ +--- +layout: post +title: Save excel to Google Drive in React Spreadsheet control | Syncfusion +description: Learn about how to Save an Excel file to Google Drive from React Spreadsheet control of Syncfusion Essential JS 2. +platform: document-processing +control: Save file to Google Drive +documentation: ug +--- + +# Save file to Google Drive + +To save a file to Google Drive in a Spreadsheet Component, you can follow the steps below + +**Step 1:** Set up Google Drive API + +You must set up a project in the Google Developers Console and enable the Google Drive API. Obtain the necessary credentials to access the API. For more information, view the official [link](https://developers.google.com/workspace/drive/api/guides/enable-sdk). + +**Step 2:** Create a Simple Spreadsheet Sample in React + +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. + +**Step 3:** Modify the `SpreadsheetController.cs` File in the Web Service Project + +* Create a web service project in .NET Core 3.0 or above. You can refer to this [link](https://www.syncfusion.com/blogs/post/host-spreadsheet-open-and-save-services) for instructions on how to create a web service project. + +* Open the `SpreadsheetController.cs` file in your web service project. + +* Import the required namespaces at the top of the file: + +```csharp + +using Google.Apis.Auth.OAuth2; +using Google.Apis.Drive.v3; +using Google.Apis.Services; +using Syncfusion.EJ2.Spreadsheet; + +``` + +* Add the following private fields and constructor parameters to the `SpreadsheetController` class, In the constructor, assign the values from the configuration to the corresponding fields. + +```csharp + +//variables for storing GDrive folderId, ApplicationName and Service-Accountkey credentials +public readonly string folderId; +public readonly string applicationName; +public readonly string credentialPath; + +//constructor for assigning credentials +public SpreadsheetController(IConfiguration configuration) +{ + folderId = configuration.GetValue("FolderId"); + credentialPath = configuration.GetValue("CredentialPath"); + applicationName = configuration.GetValue("ApplicationName"); +} + +``` + +* Create the `SaveExcelToGoogleDrive()` method to save the document to the Google Drive. + +```csharp + +[HttpPost] +[Route("SaveExcelToGoogleDrive")] +public async Task SaveExcelToGoogleDrive([FromForm] SaveSettings saveSettings) +{ + try + { + //Generate Excel file stream using Syncfusion + Stream generatedStream = Workbook.Save(saveSettings); + //Copy to MemoryStream to ensure full content is flushed and seekable + MemoryStream excelStream = new MemoryStream(); + // Copy generated stream to MemoryStream for upload + await generatedStream.CopyToAsync(excelStream); + excelStream.Position = 0; // Reset position for upload + // Prepare file name with extension based on SaveType + string fileName = saveSettings.FileName + "." + saveSettings.SaveType.ToString().ToLower(); + // Validate service account credential file + if (!System.IO.File.Exists(credentialPath)) + throw new FileNotFoundException($"Service account key file not found at {credentialPath}"); + //Authenticate using Service Account credentials + GoogleCredential credential; + // Load Google service account credentials + using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read)) + { + credential = GoogleCredential.FromStream(streamKey) + .CreateScoped(DriveService.Scope.Drive); + } + //Initialize Google Drive API service + var service = new DriveService(new BaseClientService.Initializer() + // Initialize Google Drive API client + { + HttpClientInitializer = credential, + ApplicationName = applicationName, + }); + //Prepare file metadata + var fileMetadata = new Google.Apis.Drive.v3.Data.File() + { + Name = fileName + }; + //Check if file already exists in the specified folder + var listRequest = service.Files.List(); + listRequest.Q = $"name='{fileName}' and trashed=false"; + // Query Google Drive for Excel, CSV files in the specified folder + listRequest.Fields = "files(id)"; + var files = await listRequest.ExecuteAsync(); + // Reset stream position before upload (important for both update and create) + excelStream.Position = 0; + // Set MIME type dynamically based on SaveType + string mimeType = saveSettings.SaveType switch + { + SaveType.Xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + SaveType.Xls => "application/vnd.ms-excel", + SaveType.Csv => "text/csv", + }; + + if (files.Files.Any()) + { + // If File exists Update in the existing file + var updateRequest = service.Files.Update(fileMetadata, files.Files[0].Id, excelStream, mimeType); + updateRequest.Fields = "id"; + await updateRequest.UploadAsync(); + } + else + { + // If File does not exist, Create new file + var createRequest = service.Files.Create(fileMetadata, excelStream,mimeType); + createRequest.Fields = "id"; + await createRequest.UploadAsync(); + } + return Ok("Excel file successfully saved/updated in Google Drive."); + } + catch (Exception ex) + { + return BadRequest("Error saving file to Google Drive: " + ex.Message); + } +} + +``` + +* Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration + +```json +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "CredentialPath": "path-to-your-service-account-key.json", + "FolderId": "your-google-drive-folder-id", + "ApplicationName": "YourAppName" +} +``` + +N> Replace the **credential path**, **folderId** and **application name** in json file with your actual Google drive folder ID , your name for your application and the path for the JSON file. + +**Step 4:** Modify the index file in the Spreadsheet sample to save the Spreadsheet as JSON data using the [`saveAsJson`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveasjson) method and send the saved JSON to the server via fetch call. + +```typescript +; + +// Save the current spreadsheet to Google Drive +const saveToGoogleDrive = () => { + // Convert spreadsheet data to JSON + spreadsheet.saveAsJson().then((json) => { + const formData = new FormData(); // Append required fields for backend API + formData.append("FileName", loadedFileInfo.fileName); // File name + formData.append("SaveType", loadedFileInfo.saveType); // Format type (Xlsx, Xls, Csv) + formData.append("JSONData", JSON.stringify(json.jsonObject.Workbook)); // Spreadsheet data + formData.append( + "PdfLayoutSettings", + JSON.stringify({ FitSheetOnOnePage: false }), + ); // PDF settings + // Make a POST request to the backend API to save the file to Google Drive. + // Replace the URL with your local or hosted endpoint URL. + fetch( + "https://localhost:your_port_number/api/spreadsheet/SaveExcelToGoogleDrive", + { + method: "POST", + body: formData, + }, + ) + .then((response) => { + if (!response.ok) throw new Error(`Save failed: ${response.status}`); + window.alert("Workbook saved successfully to Google Drive."); + }) + .catch((error) => { + window.alert("Error saving to Google Drive: " + error); + }); + }); +}; +``` + +N> The Google.Apis.Drive.v3 NuGet package must be installed in your application to use the previous code example. + +[View sample in GitHub](https://github.com/SyncfusionExamples/syncfusion-react-spreadsheet-google-drive-integration) diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-files.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-files.md new file mode 100644 index 0000000000..122df0ab53 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/save-excel-files.md @@ -0,0 +1,484 @@ +--- +layout: post +title: Save Excel Files in React Spreadsheet component | Syncfusion +description: Learn here all about Saving Excel files in Syncfusion React Spreadsheet component of Syncfusion Essential JS 2 and more. +platform: document-processing +control: Save +documentation: ug +--- + +# Save Excel Files in Syncfusion React Spreadsheet + +The [React Spreadsheet Editor](https://www.syncfusion.com/spreadsheet-editor-sdk/react-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`](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core) library is used to convert the JSON data into a fully formatted Excel file. This library is built on top of [`Syncfusion XlsIO`](https://help.syncfusion.com/document-processing/excel/excel-library/net/overview), 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. + +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. + +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: + +```csharp +// Save action +[HttpPost] +[Route("Save")] +public IActionResult Save([FromForm] SaveSettings saveSettings) +{ + if(saveSettings && 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](./web-services/webservice-overview) 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](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core)
[Syncfusion.EJ2.AspNet.Core](https://www.nuget.org/packages/Syncfusion.EJ2.AspNet.Core)
[Syncfusion.XlsIORenderer.Net.Core](https://www.nuget.org/packages/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](https://www.nuget.org/packages/Syncfusion.XlsIO.AspNet.Mvc5)
[Syncfusion.ExcelToPdfConverter.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.ExcelToPdfConverter.AspNet.Mvc5)
[Syncfusion.Pdf.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.Pdf.AspNet.Mvc5/)
[Syncfusion.ExcelChartToImageConverter.AspNet.Mvc5](https://www.nuget.org/packages/Syncfusion.ExcelChartToImageConverter.AspNet.Mvc5)
[Syncfusion.EJ2.MVC5](https://www.nuget.org/packages/Syncfusion.EJ2.MVC5) | + +For more details, see the [dependencies section on nuget.org](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core#dependencies-body-tab). + +To enable saving Excel files, set the [`allowSave`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowsave) property to **true** and specify the service URL using the [`saveUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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: +{% youtube "https://www.youtube.com/watch?v=MpwiXmL1Z_o" %} + +## 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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveurl) property in the Spreadsheet control. You can also use the [`beforeSave`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event to customize or cancel the save action which gets triggered before saving the Spreadsheet as an Excel file. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs5/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs5/app/app.tsx %} +{% endhighlight %} +{% highlight js tabtitle="datasource.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs5/app/datasource.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="datasource.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs5/app/datasource.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs5" %} + +Please find the below table for the [`beforeSave`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowsave) property is `true`. For demonstration purpose, we have showcased the [allowSave](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#save) method of the Spreadsheet component. Before invoking this method, ensure that the [`saveUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#save) method arguments. + +| **Parameter** | **Type** | **Description** | +|-----------------------|------------------------|------------------------------------------------------------------| +| options | [`SaveOptions`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/saveoptions) | Options for opening the JSON object. | +| jsonConfig *(optional)* | [`SerializationOptions`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/serializationOptions) | Specify the serialization options to customize the loading of the JSON data. | + +The following code example demonstrates how to save an Excel file programmatically in the Spreadsheet. + +```js +import React, { useRef } from 'react'; +import { createRoot } from 'react-dom/client'; +import { salesData } from './data'; +import { SpreadsheetComponent, SheetsDirective, RangesDirective, RangeDirective,SheetDirective} from '@syncfusion/ej2-react-spreadsheet'; + +const App = () => { + const spreadsheetRef = useRef(null); + const onClick = () => { + spreadsheetRef.current?.save({ + url: 'https://document.syncfusion.com/web-services/spreadsheet-editor/api/spreadsheet/save', + fileName: 'Worksheet', + saveType: 'Xlsx', + }); + }; + + return ( +
+ + + + + + + + + + +
+ ); +}; + +export default App; + +const root = createRoot(document.getElementById('spreadsheet')); +root.render(); +``` + +## 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event of the spreadsheet. Subsequently, you will receive the spreadsheet data as a blob in the [saveComplete](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/save-as-blobdata-cs1/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/save-as-blobdata-cs1/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/save-as-blobdata-cs1" %} + +### 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/save-as-json-cs1/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/save-as-json-cs1/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/save-as-json-cs1" %} + +### 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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**: + +```js + + // Convert the spreadsheet workbook to JSON data. + 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**: + +```csharp + public string Save(SaveSettings saveSettings) + { + try + { + // Save the workbook as stream. + Stream fileStream = Workbook.Save(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); + // To convert the stream to file options. + 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](https://www.syncfusion.com/downloads/support/directtrac/general/ze/WebApplication1_(1)-880363187). After launching the server endpoint, you need to update the URL on the client side sample as shown below. + +```js +//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](https://support.syncfusion.com/kb/article/17184/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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. After that, convert the spreadsheet data into JSON format using the [saveAsJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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. + +```js +function Default() { + let spreadsheet; + let saveInitiated; + const beforeSaveHandler = (eventArgs) => { + if (!saveInitiated) { + eventArgs.cancel = true; // Preventing default save action. + saveInitiated = true; // The "beforeSave" event will trigger for "saveAsJson" action also, so we are preventing for the "saveAsJson". + saveAsExcel(eventArgs); + } + }; + const saveAsExcel = (eventArgs) => { + // Convert the spreadsheet workbook to JSON data. + spreadsheet.saveAsJson().then(Json => { + saveInitiated = false; + const formData = new FormData(); + // Passing the JSON data to server to perform save operation. + formData.append('JSONData', JSON.stringify(Json.jsonObject.Workbook)); + formData.append('saveType', 'Xlsx'); + formData.append('fileName', 'Worksheet'); + formData.append('pdfLayoutSettings', '{"fitSheetOnOnePage":false,"orientation":"Portrait"}'); + // Using fetch API to invoke the server for save processing. + fetch('https://xxxxxxxxxxxxxxxxxxxxxxxxx.amazonaws.com/Prod/api/spreadsheet/save', { + method: 'POST', body: formData + }).then(response => { + if (response.ok) { + return response.blob(); + } + }).then(data => { + const reader = new FileReader(); + reader.onload = function () { + //Converts the result of the file reading operation into a base64 string. + const textBase64Str = reader.result.toString(); + //Converts the base64 string into a Excel base64 string. + const excelBase64Str = atob(textBase64Str.replace('data:text/plain;base64,', '')); + //Converts the Excel base64 string into byte characters. + const byteCharacters = atob(excelBase64Str.replace('data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,', '')); + const byteArrays = []; + for (let i = 0; i < byteCharacters.length; i++) { + byteArrays.push(byteCharacters.charCodeAt(i)); + } + const byteArray = new Uint8Array(byteArrays); + //creates a blob data from the byte array with xlsx content type. + const blobData = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); + const blobUrl = URL.createObjectURL(blobData); + const anchor = document.createElement('a'); + anchor.download = 'Sample.xlsx'; + anchor.href = blobUrl; + document.body.appendChild(anchor); + anchor.click(); + URL.revokeObjectURL(blobUrl); + document.body.removeChild(anchor); + } + reader.readAsDataURL(data); + }); + }); + }; + return (
+
+ { spreadsheet = ssObj; }} beforeSave={beforeSaveHandler}> + +
+
); +} +export default Default; +``` + +```csharp +public string Save([FromForm]SaveSettings saveSettings) +{ + // This will return the Excel in base64 string format. + return Workbook.Save(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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#savecomplete) event when you set the `needBlobData` as **true** and `isFullPost` as **false** in the [beforeSave](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. + +The following code example shows how to save the spreadsheet data as base64 string. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/base-64-string/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/base-64-string/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/base-64-string" %} + +## Advanced Save options + +### Configure JSON serialization + +Previously, when saving the Spreadsheet as a workbook JSON object using the [saveAsJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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. + +```ts +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: + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/save-as-json/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/save-as-json/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/save-as-json" %} + +## Customization + +### Pass custom parameters during Save + +Passing the custom parameters from client to server by using [`beforeSave`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs6/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs6/app/app.tsx %} +{% endhighlight %} +{% highlight js tabtitle="datasource.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs6/app/datasource.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="datasource.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs6/app/datasource.tsx %} +{% endhighlight %} +{% endtabs %} + + {% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs6" %} +Server side code snippets: + +```csharp + + 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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#filemenuitemselect) event, the custom header can be added to the request during save action. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs7/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs7/app/app.tsx %} +{% endhighlight %} +{% highlight js tabtitle="datasource.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs7/app/datasource.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="datasource.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs7/app/datasource.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs7" %} + +### 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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. + +The possible values are: + +* **Portrait** - Used to display content in a vertical layout. +* **Landscape** - Used to display content in a horizontal layout. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs8/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs8/app/app.tsx %} +{% endhighlight %} +{% highlight js tabtitle="datasource.jsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs8/app/datasource.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="datasource.tsx" %} +{% include code-snippet/spreadsheet/react/open-save-cs8/app/datasource.tsx %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs8" %} From ab8ae3b6e5708d69e8ab0fc393998ddc32f773ef Mon Sep 17 00:00:00 2001 From: MOHANRAJSF4991 Date: Fri, 14 Aug 2026 14:13:22 +0530 Subject: [PATCH 2/4] 1029584: updated open and save file --- .../open-excel-file/from-aws-s3-bucket.md | 10 +++++----- .../open-excel-file/from-azure-blob-storage.md | 10 +++++----- .../open-excel-file/from-google-cloud-storage.md | 10 +++++----- .../open-excel-file/from-google-drive.md | 16 +++++++--------- .../save-excel-file/to-aws-s3-bucket.md | 10 +++++----- .../save-excel-file/to-azure-blob-storage.md | 10 +++++----- .../save-excel-file/to-google-cloud-storage.md | 10 +++++----- .../save-excel-file/to-google-drive.md | 14 ++++++-------- 8 files changed, 43 insertions(+), 47 deletions(-) diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md index 62eac0fcc3..ada432257d 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-aws-s3-bucket.md @@ -1,19 +1,19 @@ --- layout: post -title: Open Excel from AWS S3 in React Spreadsheet Control | Syncfusion -description: How to open an Excel file from AWS S3 in the React Spreadsheet control of Syncfusion Essential JS 2 and more details. +title: Opening excel from AWS S3 in ASP.NET Core Spreadsheet Control | Syncfusion +description: Learn about how to Open an Excel file from AWS S3 in EJ2 ASP.NET Core Spreadsheet control of Syncfusion Essential JS 2 and more details. platform: document-processing control: Open file from AWS S3 documentation: ug --- -# Open file from AWS S3 +# Open file from AWS S3 in ASP.NET Core Spreadsheet To load a file from AWS S3 in a Spreadsheet Component, you can follow the steps below -**Step 1:** Create a Simple Spreadsheet Sample in React +**Step 1:** Create a Simple Spreadsheet Sample in ASP.NET Core -Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/asp-net-core/getting-started-core) to create a simple Spreadsheet sample in ASP.NET Core. This will give you a basic setup of the Spreadsheet component. **Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md index cb3ce3789f..cb0ab17c2c 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-azure-blob-storage.md @@ -1,19 +1,19 @@ --- layout: post -title: Open excel from Azure Blob in React Spreadsheet control | Syncfusion -description: Learn about how to Open an Excel file from Azure Blob Storage in React Spreadsheet control of Syncfusion Essential JS 2. +title: Open excel from Azure Blob in ASP.NET Core Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from Azure Blob Storage in EJ2 ASP.NET Core Spreadsheet control of Syncfusion Essential JS 2. platform: document-processing control: Open file from Azure Blob Storage documentation: ug --- -# Open file from Azure Blob Storage +# Open file from Azure Blob Storage in ASP.NET Core To load a file from Azure Blob Storage in a Spreadsheet Component, you can follow the steps below -**Step 1:** Create a Simple Spreadsheet Sample in React +**Step 1:** Create a Simple Spreadsheet Sample in ASP.NET Core -Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/asp-net-core/getting-started-core) to create a simple Spreadsheet sample in ASP.NET Core. This will give you a basic setup of the Spreadsheet component. **Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md index d691482fe4..8b1185d697 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-cloud-storage.md @@ -1,19 +1,19 @@ --- layout: post -title: Open excel from Google Cloud in React Spreadsheet control | Syncfusion -description: Learn about how to Open an Excel file from Google Cloud Storage in React Spreadsheet control of Syncfusion Essential JS 2. +title: Open excel from Google Cloud in ASP.NET Core Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from Google Cloud Storage in EJ2 ASP.NET Core Spreadsheet control of Syncfusion Essential JS 2. platform: document-processing control: Open file from Google Cloud Storage documentation: ug --- -# Open file from Google Cloud Storage +# Open file from Google Cloud Storage in ASP.NET Core To load a file from Google Cloud Storage in a Spreadsheet Component, you can follow the steps below -**Step 1:** Create a Simple Spreadsheet Sample in React +**Step 1:** Create a Simple Spreadsheet Sample in ASP.NET Core -Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/asp-net-core/getting-started-core) to create a simple Spreadsheet sample in ASP.NET Core. This will give you a basic setup of the Spreadsheet component. **Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md index e387f50fb1..56910db51c 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/open-excel-file/from-google-drive.md @@ -1,13 +1,13 @@ --- layout: post -title: Open excel from Google Drive in React Spreadsheet control | Syncfusion -description: Learn about how to Open an Excel file from Google Drive in React Spreadsheet control of Syncfusion Essential JS 2. +title: Open excel from Google Drive in EJ2 ASP.NET Core Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from Google Drive in EJ2 ASP.NET Core Spreadsheet control of Syncfusion Essential JS 2. platform: document-processing control: Open file from Google Drive documentation: ug --- -# Open file from Google Drive +# Open file from Google Drive in ASP.NET Core Spreadsheet To load a file from Google Drive in a Spreadsheet Component, you can follow the steps below @@ -15,9 +15,9 @@ To load a file from Google Drive in a Spreadsheet Component, you can follow the You must set up a project in the Google Developers Console and enable the Google Drive API. Obtain the necessary credentials to access the API. For more information, view the official [link](https://developers.google.com/workspace/drive/api/guides/enable-sdk). -**Step 2:** Create a Simple Spreadsheet Sample in React +**Step 2:** Create a Simple Spreadsheet Sample in ASP.NET Core -Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. +Start by following the steps provided in this [link](https://help.syncfusion.com/document-processing/excel/spreadsheet/asp-net-core/getting-started-core) to create a simple Spreadsheet sample in ASP.NET Core. This will give you a basic setup of the Spreadsheet component. **Step 3:** Modify the `SpreadsheetController.cs` File in the Web Service Project @@ -149,7 +149,7 @@ public class FileOptions N> Replace the **credential path**, **folderId** and **application name** in json file with your actual Google drive folder ID , your name for your application and the path for the JSON file. -**Step 4:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and process the Excel file from the Google Drive and load the JSON result into the client-side spreadsheet using the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method. +**Step 4:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and process the Excel file from the Google Drive and load the JSON result into the client-side spreadsheet using the [openFromJson](https://ej2.syncfusion.com/javascript/documentation/api/spreadsheet/index-default#openfromjson) method. ```typescript - - ); -}; - -export default App; - -const root = createRoot(document.getElementById('spreadsheet')); -root.render(); -``` +{% tabs %} +{% highlight cshtml tabtitle="CSHTML" %} +@{ + ViewBag.SalesData = new List() + { + new { CustomerName = "Romona Heaslip", Model = "Taurus", Color = "Aquamarine", PaymentMode = "Debit Card", DeliveryDate = "07/11/2015", Amount = "8529.22" }, + new { CustomerName = "Clare Batterton", Model = "Sparrow", Color = "Pink", PaymentMode = "Cash On Delivery", DeliveryDate = "7/13/2016", Amount = "17866.19" }, + new { CustomerName = "Eamon Traise", Model = "Grand Cherokee", Color = "Blue", PaymentMode = "Net Banking", DeliveryDate = "09/04/2015", Amount = "13853.09" } + }; +} + +
+ + + + + + + + + + +
+ + +{% endhighlight %} +{% endtabs %} ## Supported Excel file formats for Save @@ -164,43 +155,36 @@ The following file formats are supported when saving the Spreadsheet component: ### 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event of the spreadsheet. Subsequently, you will receive the spreadsheet data as a blob in the [saveComplete](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#savecomplete) event. You can then post the blob data to the server endpoint for saving. +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](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_BeforeOpen) event of the spreadsheet. Subsequently, you will receive the spreadsheet data as a blob in the [saveComplete](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_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. {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/save-as-blobdata-cs1/app/app.jsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/save-as-blob/tagHelper %} {% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/save-as-blobdata-cs1/app/app.tsx %} +{% highlight c# tabtitle="SaveController.cs" %} +{% include code-snippet/spreadsheet/asp-net-core/save-as-blob/savecontroller.cs %} {% endhighlight %} {% endtabs %} -{% previewsample "/document-processing/code-snippet/spreadsheet/react/save-as-blobdata-cs1" %} - ### 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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. +You can optionally pass serialization options to the [saveAsJson](https://ej2.syncfusion.com/javascript/documentation/api/spreadsheet/index-default#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. {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/save-as-json-cs1/app/app.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/save-as-json-cs1/app/app.tsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/save-as-json-cs1/tagHelper %} {% endhighlight %} {% endtabs %} -{% previewsample "/document-processing/code-snippet/spreadsheet/react/save-as-json-cs1" %} - ### 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#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. +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](https://ej2.syncfusion.com/javascript/documentation/api/spreadsheet/index-default#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**: @@ -264,24 +248,30 @@ Before proceeding with the save process, you should deploy the spreadsheet open/ [How to deploy a spreadsheet open and save web API service to AWS Lambda](https://support.syncfusion.com/kb/article/17184/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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. After that, convert the spreadsheet data into JSON format using the [saveAsJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveasjson) method in the `beforeSave` event and send it to the save service endpoint URL using a fetch request. +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`](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_BeforeSave) event. After that, convert the spreadsheet data into JSON format using the [saveAsJson](https://ej2.syncfusion.com/javascript/documentation/api/spreadsheet/index-default#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. -```js -function Default() { - let spreadsheet; - let saveInitiated; - const beforeSaveHandler = (eventArgs) => { +{% tabs %} +{% highlight cshtml tabtitle="CSHTML" %} + + + + + + + +{% endhighlight %} +{% endtabs %} ```csharp public string Save([FromForm]SaveSettings saveSettings) @@ -349,26 +334,24 @@ public string Save([FromForm]SaveSettings saveSettings) 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](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#savecomplete) event when you set the `needBlobData` as **true** and `isFullPost` as **false** in the [beforeSave](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. +> You can get the Spreadsheet data as blob in the [saveComplete](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_SaveComplete) event when you set the `needBlobData` as **true** and `isFullPost` as **false** in the [beforeSave](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_BeforeSave) event. The following code example shows how to save the spreadsheet data as base64 string. {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/base-64-string/app/app.jsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/base-64-string/tagHelper %} {% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/base-64-string/app/app.tsx %} +{% highlight c# tabtitle="OpenController.cs" %} +{% include code-snippet/spreadsheet/asp-net-core/base-64-string/opencontroller.cs %} {% endhighlight %} {% endtabs %} -{% previewsample "/document-processing/code-snippet/spreadsheet/react/base-64-string" %} - ## Advanced Save options ### Configure JSON serialization -Previously, when saving the Spreadsheet as a workbook JSON object using the [saveAsJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveasjson) method, the entire workbook with all loaded features were processed and saved as a JSON object. +Previously, when saving the Spreadsheet as a workbook JSON object using the [saveAsJson](https://ej2.syncfusion.com/javascript/documentation/api/spreadsheet/index-default#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. @@ -393,38 +376,28 @@ spreadsheet.saveAsJson({ onlyValues: true }); The following code snippet demonstrates how to configure the serialization options and pass them as arguments to the saveAsJson method: {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/save-as-json/app/app.jsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/save-as-json/tagHelper %} {% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/save-as-json/app/app.tsx %} +{% highlight c# tabtitle="SaveController.cs" %} +{% include code-snippet/spreadsheet/asp-net-core/save-as-json/saveController.cs %} {% endhighlight %} {% endtabs %} -{% previewsample "/document-processing/code-snippet/spreadsheet/react/save-as-json" %} - ## Customization ### Pass custom parameters during Save -Passing the custom parameters from client to server by using [`beforeSave`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. +Passing the custom parameters from client to server by using [`beforeSave`](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_BeforeSave) event. {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs6/app/app.jsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/custom-params/tagHelper %} {% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs6/app/app.tsx %} -{% endhighlight %} -{% highlight js tabtitle="datasource.jsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs6/app/datasource.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="datasource.tsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs6/app/datasource.tsx %} +{% highlight c# tabtitle="CustomParamsController.cs" %} +{% include code-snippet/spreadsheet/asp-net-core/custom-params/customParamsController.cs %} {% endhighlight %} {% endtabs %} - - {% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs6" %} Server side code snippets: ```csharp @@ -438,28 +411,20 @@ Server side code snippets: ### 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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#filemenuitemselect) event, the custom header can be added to the request during save action. +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`](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_FileMenuItemSelect) event, the custom header can be added to the request during save action. {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs7/app/app.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs7/app/app.tsx %} -{% endhighlight %} -{% highlight js tabtitle="datasource.jsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs7/app/datasource.jsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/save-header/tagHelper %} {% endhighlight %} -{% highlight ts tabtitle="datasource.tsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs7/app/datasource.tsx %} +{% highlight c# tabtitle="CustomHeaderController.cs" %} +{% include code-snippet/spreadsheet/asp-net-core/save-header/CustomHeaderController.cs %} {% endhighlight %} {% endtabs %} -{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs7" %} - ### 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`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforesave) event. +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`](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_BeforeSave) event. The possible values are: @@ -467,18 +432,10 @@ The possible values are: * **Landscape** - Used to display content in a horizontal layout. {% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs8/app/app.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs8/app/app.tsx %} +{% highlight cshtml tabtitle="CSHTML" %} +{% include code-snippet/spreadsheet/asp-net-core/pdf-orientation/tagHelper %} {% endhighlight %} -{% highlight js tabtitle="datasource.jsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs8/app/datasource.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="datasource.tsx" %} -{% include code-snippet/spreadsheet/react/open-save-cs8/app/datasource.tsx %} +{% highlight c# tabtitle="pdfOrientationController.cs" %} +{% include code-snippet/spreadsheet/asp-net-core/pdf-orientation/pdfOrientationController.cs %} {% endhighlight %} {% endtabs %} - -{% previewsample "/document-processing/code-snippet/spreadsheet/react/open-save-cs8" %} diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md index 0295ef68a9..0de98664bb 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md @@ -86,6 +86,6 @@ Once deployed, your app will be live at https://XXXXXXXXXX.azurewebsites.net. openUrl="https://XXXXXXXXXX.azurewebsites.net/api/spreadsheet/open" saveUrl="https://XXXXXXXXXX.azurewebsites.net/api/spreadsheet/save ``` -Append the App Service running URL to the service URL in the client‑side Spreadsheet Editor component. For more information about how to get started with the Spreadsheet Editor component, refer to this [`getting started page`](../getting-started) +Append the App Service running URL to the service URL in the client‑side Spreadsheet Editor component. For more information about how to get started with the Spreadsheet Editor component, refer to this [`getting started page`](../getting-started-core) For more information about the app container service, please look deeper into the [`Microsoft Azure App Service`](https://docs.microsoft.com/en-us/visualstudio/deployment/) for a production-ready setup. \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-server-to-aws-eks-using-docker.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-server-to-aws-eks-using-docker.md index b9fe429ad9..bd3694c71c 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-server-to-aws-eks-using-docker.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/deploy-spreadsheet-server-to-aws-eks-using-docker.md @@ -1,7 +1,7 @@ --- layout: post title: Deploy Spreadsheet Docker to AWS EKS Cluster | Syncfusion -description: Learn how to deploy the Syncfusion Spreadsheet server Docker image to AWS EKS and connect it to the React Spreadsheet component. +description: Learn how to deploy the Syncfusion Spreadsheet server Docker image to AWS EKS and connect it to the EJ2 ASP.NET Core Spreadsheet component. control: How to deploy spreadsheet server to AWS EKS using Docker platform: document-processing documentation: ug @@ -113,16 +113,17 @@ kubectl get svc spreadsheet-server-service * Retrieve the external address from the Service output. Use `https://` only if the Load Balancer is configured with TLS (use ACM for certificates). -**Step 5:** Configure the React client +**Step 5:** Configure the ASP.NET Core client -Start by following the steps provided in this [link](../getting-started) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. Once the Service reports an external address (e.g., a1b2c3d4e5f6-1234567890.us-east-1.elb.amazonaws.com), update the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) and [`saveUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveurl) properties of your React Spreadsheet component: +Start by following the steps provided in this [link](../getting-started-core) to create a simple Spreadsheet sample in ASP.NET Core. This will give you a basic setup of the Spreadsheet component. Once the Service reports an external address (e.g., a1b2c3d4e5f6-1234567890.us-east-1.elb.amazonaws.com), update the [`openUrl`](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_OpenUrl) and [`saveUrl`](https://help.syncfusion.com/cr/aspnetcore-js2/Syncfusion.EJ2.Spreadsheet.Spreadsheet.html#Syncfusion_EJ2_Spreadsheet_Spreadsheet_SaveUrl) properties of your ASP.NET Core Spreadsheet component: -```js +```cshtml - + + ``` @@ -136,6 +137,6 @@ Start by following the steps provided in this [link](../getting-started) to crea For more information on deploying Spreadsheet docker image in Amazon EKS kindly refer to this [`Blog`](https://www.syncfusion.com/blogs/post/spreadsheet-server-eks-deployment) ## See Also -* [Docker Image Overview in React Spreadsheet](./spreadsheet-server-docker-image-overview) +* [Docker Image Overview in ASP.NET Core Spreadsheet](./spreadsheet-server-docker-image-overview) * [Publish Spreadsheet Server to Azure App Service using Visual Studio](./publish-spreadsheet-server-to-azure-using-visual-studio) * [Deploy Spreadsheet Docker to Azure App Service using Azure CLI](./deploy-spreadsheet-docker-to-azure-using-azure-cli) \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md index 19391af422..296c2c625d 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md @@ -52,6 +52,6 @@ https://XXXXXXXXXX.azurewebsites.net openUrl="https://XXXXXXXXXX.azurewebsites.net/api/spreadsheet/open" saveUrl="https://XXXXXXXXXX.azurewebsites.net/api/spreadsheet/save ``` -Append the App Service running URL to the service URL in the client‑side Spreadsheet Editor component. For more information about how to get started with the Spreadsheet Editor component, refer to this [`getting started page`](../getting-started) +Append the App Service running URL to the service URL in the client‑side Spreadsheet Editor component. For more information about how to get started with the Spreadsheet Editor component, refer to this [`getting started page`](../getting-started-core) For more information about the app container service, please look deeper into the [`Microsoft Azure App Service`](https://docs.microsoft.com/en-us/visualstudio/deployment/) for a production-ready setup. \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/spreadsheet-server-docker-image-overview.md b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/spreadsheet-server-docker-image-overview.md index 040604c960..35e1c0542b 100644 --- a/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/spreadsheet-server-docker-image-overview.md +++ b/Document-Processing/Excel/Spreadsheet/ASP-NET-CORE/server-deployment/spreadsheet-server-docker-image-overview.md @@ -1,17 +1,17 @@ --- layout: post -title: Docker image deployment in React Spreadsheet component | Syncfusion -description: Learn here all about Docker image deployment in Syncfusion React Spreadsheet component of Syncfusion Essential JS 2 and more. +title: Docker image deployment in EJ2 ASP.NET Core Spreadsheet component | Syncfusion +description: Learn here all about Docker image deployment in Syncfusion EJ2 ASP.NET Core Spreadsheet component of Syncfusion Essential JS 2 and more. platform: document-processing control: Docker deployment documentation: ug --- -# Docker Image Overview in React Spreadsheet +# Docker Image Overview in ASP.NET Core Spreadsheet -The [React Spreadsheet Editor](https://www.syncfusion.com/spreadsheet-editor-sdk/react-spreadsheet-editor) component is a feature-rich control for organizing and analyzing data in a tabular format. It provides all the common Excel features, including data binding, selection, editing, formatting, resizing, sorting, filtering, importing, and exporting Excel documents. +The [ASP.NET Core Spreadsheet Editor](https://www.syncfusion.com/spreadsheet-editor-sdk/react-spreadsheet-editor) component is a feature-rich control for organizing and analyzing data in a tabular format. It provides all the common Excel features, including data binding, selection, editing, formatting, resizing, sorting, filtering, importing, and exporting Excel documents. -This Docker image is the pre-defined Docker container for React Spreadsheet back-end functionalities. This server-side Web API project targets ASP.NET Core 8.0. +This Docker image is the pre-defined Docker container for ASP.NET Core Spreadsheet back-end functionalities. This server-side Web API project targets ASP.NET Core 8.0. You can deploy it quickly to your infrastructure. If you want to add new functionality or customize any existing functionalities, create your own Docker file by referencing the existing [Spreadsheet Docker project](https://github.com/SyncfusionExamples/Spreadsheet-Server-Docker). @@ -59,23 +59,16 @@ Now the Spreadsheet server Docker instance runs on localhost with the provided p **Step 4:** Append the URLs of the Docker instance running services to the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property as `http://localhost:6002/api/spreadsheet/open` and the [`saveUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveurl) property as `http://localhost:6002/api/spreadsheet/save` in the client-side Spreadsheet component. For more information on how to get started with the Spreadsheet component, refer to this [`getting started page.`](https://help.syncfusion.com/document-processing/excel/spreadsheet/react/getting-started) -```js -import * as React from 'react'; -import { createRoot } from 'react-dom/client'; -import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet'; +{% tabs %} +{% highlight cshtml tabtitle="CSHTML" %} -function App() { + + - return ( - // Initialize Spreadsheet component. - - ); -}; -export default App; - -const root = createRoot(document.getElementById('root')); -root.render(); -``` +{% endhighlight %} +{% endtabs %} ## How to configure different cultures using a Docker compose file