diff --git a/Document-Processing-toc.html b/Document-Processing-toc.html index 20910f23de..f002eee8ac 100644 --- a/Document-Processing-toc.html +++ b/Document-Processing-toc.html @@ -5274,8 +5274,27 @@
  • Getting Started
  • Getting Started with NextJS
  • Data Binding
  • -
  • Open and Save
  • -
  • Docker Deployment
  • +
  • Open Excel Files + +
  • +
  • Save Excel Files + +
  • +
  • Server Deployment + +
  • Worksheet
  • Cell Range
  • Editing
  • diff --git a/Document-Processing/Excel/Spreadsheet/React/Open-Excel-File/from-aws-s3-bucket.md b/Document-Processing/Excel/Spreadsheet/React/Open-Excel-File/from-aws-s3-bucket.md new file mode 100644 index 0000000000..724e02e9b3 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/Open-Excel-File/from-aws-s3-bucket.md @@ -0,0 +1,176 @@ +--- +layout: post +title: Opening excel from AWS S3 in React Spreadsheet control | Syncfusion +description: Learn about how to Open an Excel file from AWS S3 in 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/React/Open-Excel-File/from-azure-blob-storage.md b/Document-Processing/Excel/Spreadsheet/React/Open-Excel-File/from-azure-blob-storage.md new file mode 100644 index 0000000000..cb3ce3789f --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/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/React/Open-Excel-File/from-google-cloud-storage.md b/Document-Processing/Excel/Spreadsheet/React/Open-Excel-File/from-google-cloud-storage.md new file mode 100644 index 0000000000..d691482fe4 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/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/React/Save-Excel-File/to-aws-s3-bucket.md b/Document-Processing/Excel/Spreadsheet/React/Save-Excel-File/to-aws-s3-bucket.md new file mode 100644 index 0000000000..1cae9284b5 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/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 a Excel file from AWS S3 in React Spreadsheet control of Syncfusion Essential JS 2 and more details. +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/React/Save-Excel-File/to-azure-blob-storage.md b/Document-Processing/Excel/Spreadsheet/React/Save-Excel-File/to-azure-blob-storage.md new file mode 100644 index 0000000000..f27c3bfc72 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/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/React/Save-Excel-File/to-google-cloud-storage.md b/Document-Processing/Excel/Spreadsheet/React/Save-Excel-File/to-google-cloud-storage.md new file mode 100644 index 0000000000..d92d4dbf3a --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/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/React/Server-Deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md b/Document-Processing/Excel/Spreadsheet/React/Server-Deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md new file mode 100644 index 0000000000..1ca888caed --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/Server-Deployment/deploy-spreadsheet-docker-to-azure-using-azure-cli.md @@ -0,0 +1,91 @@ +--- +layout: post +title: Deploy Spreadsheet Server to Azure App Service using CLI | Syncfusion +description: Learn how to deploy the Syncfusion Spreadsheet Server Docker image to Azure App Service using Azure CLI. +control: How to deploy Spreadsheet Server Docker Image to Azure App Service using Azure CLI +platform: document-processing +documentation: ug +--- + +# Deploy Spreadsheet Docker to Azure App Service using Azure CLI + +## Prerequisites + +* `Docker` installed on your machine (Windows, macOS, or Linux). +* `Azure CLI` installed based on your operating system. [Download Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) +* An active [`Azure subscription`](https://azure.microsoft.com/en-gb) with App Services access. +* The [`Spreadsheet Server Docker image`](https://hub.docker.com/r/syncfusion/spreadsheet-server) available. + +## Deploy to Azure App Service using Azure CLI + +**Step 1:** Log in to Azure + +Open your terminal and sign in to Azure using the command below. This authenticates your CLI with Azure. + +```bash +az login +``` + +**Step 2:** Create a resource group + +Create a resource group with the following command in your preferred location. + +```bash +az group create --name < your-app-name> --location +``` + +**Step 3:** Create an app service plan + +Create a resource group with the following command in your preferred location. + +```bash +az appservice plan create --name --resource-group < your-resource-group> --sku S1 --is-linux +``` + +This creates an App Service plan in the standard pricing tier (S1) and ensures it runs on Linux containers with the --is-linux flag. + +**Step 4:** Create the docker-compose.yml file + +Define your container configuration in a docker-compose.yml file. This file specifies the container name, image, and environment variables for the Spreadsheet Server: + +```bash +version: '3.4' + +services: + spreadsheet-server: + image: syncfusion/spreadsheet-server + environment: + + # Provide your license key for activation + SYNCFUSION_LICENSE_KEY: YOUR_LICENSE_KEY + ports: + - "6002:8080" + +``` + +Note: Replace YOUR_LICENSE_KEY with your valid Syncfusion license key. + +**Step 5:** Create a Docker compose app + +Deploy the containerized app to Azure App Service using the following command. + +```bash +az webapp create --resource-group --plan < your-app-service-plan> --name --multicontainer-config-type compose --multicontainer-config-file docker-compose.yml +``` + +This command creates a web app that runs your Spreadsheet Server Docker container using the configuration defined in the docker-compose.yml file. + +**Step 6:** Browse your app + +Once deployed, your app will be live at https://XXXXXXXXXX.azurewebsites.net. + +![azure cli](../images/azure-cli.png) + +**Step 7:** With your server running, verify that it supports import and export operations by testing the following endpoints: +``` +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.md) + +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/React/Server-Deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md b/Document-Processing/Excel/Spreadsheet/React/Server-Deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md new file mode 100644 index 0000000000..1c50b61223 --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/Server-Deployment/publish-spreadsheet-server-to-azure-using-visual-studio.md @@ -0,0 +1,57 @@ +--- +layout: post +title: Deploy Spreadsheet Server to Azure App Service via VS | Syncfusion +description: Learn how to publish the Syncfusion Spreadsheet Server Web API to Azure App Service using Visual Studio. +control: How to publish Spreadsheet Server in Azure App Service using Visual Studio +platform: document-processing +documentation: ug +--- + +# Publish Spreadsheet Server to Azure App Service using Visual Studio + + +## Prerequisites + +* `Visual Studio 2022` or later is installed. +* [`.NET 8.0 SDK`](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) or later installed. +* An active [`Azure subscription`](https://azure.microsoft.com/en-gb) with App Services access. +* The [`Spreadsheet Web API project`](https://github.com/SyncfusionExamples/EJ2-Spreadsheet-WebServices/tree/main/WebAPI) repository cloned locally. + +Make sure you build the project using the Build > Build Solution menu command before following the deployment steps. + +## Publish to Azure App Service + +**Step 1:** In Solution Explorer, right-click the project and click Publish (or use the Build > Publish menu item). + +![azure publish ](../images/azure_publish.png) + +**Step 2:** In the Pick a publish target dialog box, select Azure as deployment target. + +![azure target ](../images/azure_target.png) + +**Step 3:** After selecting Azure, choose Azure App Service under the target options. + +![azure app service](../images/azure_app_service.png) + +**Step 4:** Select Publish. The Create App Service dialog box appears. Sign in with your Azure account, if necessary, and then the default app service settings populate the fields. + +![azure credentials](../images/azure_credentials.png) + +**Step 5:** Select Create. Visual Studio deploys the app to your Azure App Service, and the web app loads in your browser with the app name at, +``` +http://.azurewebsites.net +``` + +![azure_published_window](../images/azure_published_window.png) + +**Step 6:** Once the deployment process is complete, The deployed API will be live at the following URL: +https://XXXXXXXXXX.azurewebsites.net + +**Step 7:** With your server running, verify that it supports import and export operations by testing the following endpoints: +``` +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.md) + +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/React/docker-deployment.md b/Document-Processing/Excel/Spreadsheet/React/Server-Deployment/spreadsheet-server-docker-image-overview.md similarity index 99% rename from Document-Processing/Excel/Spreadsheet/React/docker-deployment.md rename to Document-Processing/Excel/Spreadsheet/React/Server-Deployment/spreadsheet-server-docker-image-overview.md index c01484870d..c96b8dc0a3 100644 --- a/Document-Processing/Excel/Spreadsheet/React/docker-deployment.md +++ b/Document-Processing/Excel/Spreadsheet/React/Server-Deployment/spreadsheet-server-docker-image-overview.md @@ -7,7 +7,7 @@ control: Docker deployment documentation: ug --- -# Docker Image Overview in React Spreadsheet component +# Docker Image Overview in React Spreadsheet The [**Syncfusion® Spreadsheet (also known as Excel Viewer)**](https://www.syncfusion.com/spreadsheet-editor-sdk/react-spreadsheet-editor) 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. diff --git a/Document-Processing/Excel/Spreadsheet/React/data-validation.md b/Document-Processing/Excel/Spreadsheet/React/data-validation.md new file mode 100644 index 0000000000..ef58cc13cd --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/data-validation.md @@ -0,0 +1,106 @@ +--- +layout: post +title: Data validation in EJ2 React Spreadsheet control | Syncfusion +description: Learn here all about Data validation in Syncfusion EJ2 React Spreadsheet control of Syncfusion Essential JS 2 and more. +platform: document-processing +control: Data validation +documentation: ug +--- + +# Data validation in EJ2 React Spreadsheet control + + +Data Validation is used to restrict the user from entering the invalid data. You can use the [`allowDataValidation`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowdatavalidation) property to enable or disable data validation. + +> * The default value for `allowDataValidation` property is `true`. + +## Apply Validation + +You can apply data validation to restrict the type of data or the values that users enter into a cell. + +You can apply data validation by using one of the following ways, + +* Select the Data tab in the Ribbon toolbar, and then choose the Data Validation item. +* Use the [`addDataValidation()`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#adddatavalidation) method programmatically. + +## Clear Validation + +Clear validation feature is used to remove data validations from the specified ranges or the whole worksheet. + +You can clear data validation rule by one of the following ways, + +* Select the Data tab in the Ribbon toolbar, and then choose the Clear Validation item. +* Use the [`removeDataValidation()`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#removedatavalidation) method programmatically. + +## Highlight Invalid Data + +Highlight invalid data feature is used to highlight the previously entered invalid values. + +You can highlight an invalid data by using one of the following ways, + +* Select the Data tab in the Ribbon toolbar, and then choose the Highlight Invalid Data item. +* Use the [`addInvalidHighlight()`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#addinvalidhighlight) method programmatically. + +## Clear Highlighted Invalid Data + +Clear highlight feature is used to remove the highlight from invalid cells. + +You can clear the highlighted invalid data by using the following ways, + +* Select the Data tab in the Ribbon toolbar, and then choose the Clear Highlight item. +* Use the [`removeInvalidHighlight()`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#removeinvalidhighlight) method programmatically. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/data-validation-cs1/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/data-validation-cs1/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + + {% previewsample "/document-processing/code-snippet/spreadsheet/react/data-validation-cs1" %} + +## Custom Data validation + +The Spreadsheet supports custom data validation, allowing users to define their own validation rules for specific cells or ranges. This feature enables you to set conditions that the entered data must meet, making it particularly useful when predefined validation options, such as numbers, dates, or lists, are insufficient. + +With custom validation, you can enforce rules using logical expressions or formulas, ensuring that only valid data is entered into the Spreadsheet. + +For example, consider a scenario where you want to ensure that a cell contains a number between 10 and 100. To achieve this, define a validation rule using a formula that checks if the entered value is greater than 10 and less than 100. The formula for this validation is =AND(A1>10, A1<100), where A1 refers to the cell being validated. + +When this rule is applied, the Spreadsheet evaluates the entered value against the formula. If a user enters a value outside the specified range, an alert notifies them of the invalid input. This helps users correct errors efficiently and ensures that only desired values are accepted. + +You can apply custom data validation using two methods. + +* The first is through the Data Validation dialog in the Ribbon toolbar. Navigate to the Data tab, select the Data Validation option, and choose the Custom type from the Allow dropdown menu. +* The second method is programmatically, using the [`addDataValidation()`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#adddatavalidation) method, which allows developers to set custom rules dynamically via code. + +The following code example demonstrates how to add custom data validation with a formula in a Spreadsheet. + +{% tabs %} +{% highlight js tabtitle="app.jsx" %} +{% include code-snippet/spreadsheet/react/data-validation-cs2/app/app.jsx %} +{% endhighlight %} +{% highlight ts tabtitle="app.tsx" %} +{% include code-snippet/spreadsheet/react/data-validation-cs2/app/app.tsx %} +{% endhighlight %} +{% endtabs %} + + {% previewsample "/document-processing/code-snippet/spreadsheet/react/data-validation-cs2" %} + +## Limitations of Data validation + +The following features have some limitations in Data Validation: + +* Entire row data validation. +* Insert row between the data validation. +* Copy/paste with data validation. +* Delete cells between data validation applied range. + +## See Also + +* [Formatting](./formatting) +* [Rows and columns](./rows-and-columns) +* [Hyperlink](./link) +* [Sorting](./sort) \ No newline at end of file diff --git a/Document-Processing/Excel/Spreadsheet/React/images/azure-cli.png b/Document-Processing/Excel/Spreadsheet/React/images/azure-cli.png new file mode 100644 index 0000000000..3ab35434c6 Binary files /dev/null and b/Document-Processing/Excel/Spreadsheet/React/images/azure-cli.png differ diff --git a/Document-Processing/Excel/Spreadsheet/React/images/azure_app_service.png b/Document-Processing/Excel/Spreadsheet/React/images/azure_app_service.png new file mode 100644 index 0000000000..13f7809126 Binary files /dev/null and b/Document-Processing/Excel/Spreadsheet/React/images/azure_app_service.png differ diff --git a/Document-Processing/Excel/Spreadsheet/React/images/azure_credentials.png b/Document-Processing/Excel/Spreadsheet/React/images/azure_credentials.png new file mode 100644 index 0000000000..7a4d584ed0 Binary files /dev/null and b/Document-Processing/Excel/Spreadsheet/React/images/azure_credentials.png differ diff --git a/Document-Processing/Excel/Spreadsheet/React/images/azure_publish.png b/Document-Processing/Excel/Spreadsheet/React/images/azure_publish.png new file mode 100644 index 0000000000..fd6cf78c9c Binary files /dev/null and b/Document-Processing/Excel/Spreadsheet/React/images/azure_publish.png differ diff --git a/Document-Processing/Excel/Spreadsheet/React/images/azure_published_window.png b/Document-Processing/Excel/Spreadsheet/React/images/azure_published_window.png new file mode 100644 index 0000000000..966c3cfc26 Binary files /dev/null and b/Document-Processing/Excel/Spreadsheet/React/images/azure_published_window.png differ diff --git a/Document-Processing/Excel/Spreadsheet/React/images/azure_target.png b/Document-Processing/Excel/Spreadsheet/React/images/azure_target.png new file mode 100644 index 0000000000..0b0692036e Binary files /dev/null and b/Document-Processing/Excel/Spreadsheet/React/images/azure_target.png differ diff --git a/Document-Processing/Excel/Spreadsheet/React/open-excel-files.md b/Document-Processing/Excel/Spreadsheet/React/open-excel-files.md new file mode 100644 index 0000000000..80c32cff3e --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/open-excel-files.md @@ -0,0 +1,555 @@ +--- +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 Syncfusion React Spreadsheet + +The React Spreadsheet component uses a server‑assisted workflow to import Excel files accurately and efficiently. When a user uploads an Excel file, the component sends the file to the server for parsing, ensuring smooth performance because the heavy processing workload is handled on the server side. + +On the server, the [`Syncfusion.EJ2.Spreadsheet library`](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core) built on top of [`Syncfusion XlsIO`](https://help.syncfusion.com/document-processing/excel/excel-library/net/overview), reads the Excel file and extracts all relevant details, including data, styles, formulas, formatting, and sheet structure. The server then converts this information into a Spreadsheet‑compatible JSON workbook. + +Once processing is complete, the JSON workbook is returned to the client, where the React Spreadsheet component renders it in the browser. This workflow preserves the original Excel layout and ensures the imported content appears with full fidelity. + +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 user interface you can open an Excel document by clicking `File > Open` menu item in ribbon. + +The following sample shows the `Open` option by using the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property in the Spreadsheet control. 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 gets 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 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 Syncfusion® Spreadsheet component, 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 }); +``` + +| Options | Description | +| ----- | ----- | +| onlyValues | If **true**, only the cell values will be loaded. | +| ignoreStyle | If **true**, styles will be excluded when loading the JSON data. | +| ignoreFormula | If **true**, formulas will be excluded when loading the JSON data. | +| ignoreFormat | If **true**, number formats will be excluded when loading the JSON data. | +| ignoreConditionalFormat | If **true**, conditional formatting will be excluded when loading the JSON data. | +| ignoreValidation | If **true**, data validation rules will be excluded when loading the JSON data. | +| ignoreFreezePane | If **true**, freeze panes will be excluded when loading the JSON data. | +| ignoreWrap | If **true**, text wrapping settings will be excluded when loading the JSON data. | +| ignoreChart | If **true**, charts will be excluded when loading the JSON data. | +| ignoreImage | If **true**, images will be excluded when loading the JSON data. | +| ignoreNote | If **true**, notes will be 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) + +## Server configuration + +In the Spreadsheet component, Excel import processing is handled on the `server‑side`. Therefore, to enable Excel importing in your application, you need to configure a server using any of the following web service technologies: + +* WebAPI +* WCF Service +* ASP.NET MVC Controller Action + +The following code example demonstrates how to configure the server using a `WebAPI` service. + +```csharp + + [Route("api/[controller]")] + public class SpreadsheetController : Controller + { + //To open Excel file + [AcceptVerbs("Post")] + [HttpPost] + [EnableCors("AllowAllOrigins")] + [Route("Open")] + public IActionResult Open(IFormCollection openRequest) + { + OpenRequest open = new OpenRequest(); + open.File = openRequest.Files[0]; + return Content(Workbook.Open(open)); + } + } +``` + +## Server dependencies + +Open helper functions are shipped in the Syncfusion.EJ2.Spreadsheet package, which is available in Essential Studio® and [`nuget.org`](https://www.nuget.org/). Following list of dependencies required for Spreadsheet open and save operations. + +* Syncfusion.EJ2 +* Syncfusion.EJ2.Spreadsheet +* Syncfusion.Compression.Base +* Syncfusion.XlsIO.Base + +And also refer [this](https://help.syncfusion.com/document-processing/excel/spreadsheet/asp-net-core/open-save#server-dependencies) for more information. diff --git a/Document-Processing/Excel/Spreadsheet/React/open-save.md b/Document-Processing/Excel/Spreadsheet/React/open-save.md deleted file mode 100644 index aa50c0db23..0000000000 --- a/Document-Processing/Excel/Spreadsheet/React/open-save.md +++ /dev/null @@ -1,894 +0,0 @@ ---- -layout: post -title: Open save in React Spreadsheet component | Syncfusion -description: Learn here all about Open save in Syncfusion React Spreadsheet component of Syncfusion Essential JS 2 and more. -control: Open save -platform: document-processing -documentation: ug ---- - -# Open save in React Spreadsheet component - -In import an Excel file, it needs to be read and converted to client side Spreadsheet model. The converted client side Spreadsheet model is sent as JSON which is used to render Spreadsheet. Similarly, when you save the Spreadsheet, the client Spreadsheet model is sent to the server as JSON for processing and saved. Server configuration is used for this process. - -To get start quickly with Open and Save, you can check on this video: - -{% youtube "https://www.youtube.com/watch?v=MpwiXmL1Z_o" %} - -## Open - -The Spreadsheet control opens an Excel document with its data, style, format, and more. To enable this feature, set [`allowOpen`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowopen) as `true` and assign service url to the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property. - -**User Interface**: - -In user interface you can open an Excel document by clicking `File > Open` menu item in ribbon. - -The following sample shows the `Open` option by using the [`openUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openurl) property in the Spreadsheet control. You can also use the [`beforeOpen`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#beforeopen) event to trigger 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 event arguments. - - | **Parameter** | **Type** | **Description** | -| ----- | ----- | ----- | -| file | FileList or string or File | To get the file stream. `FileList` - contains length and item index.
    `File` - specifies the file lastModified and file name. | -| cancel | boolean | To prevent the open operation. | -| requestData | object | To provide the Form data. | - -> * 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 an excel file using a file uploader - -If you explore your machine to select and upload an Excel document using the file uploader, 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 uploader. 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 uploader 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 an external URL excel file while initial load - -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 an excel file 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/index-default#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" %} - -### Open an Excel file located on a server - -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 an excel file using a hosted web service in 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 an excel file from Base64 string data - -In the Syncfusion® Spreadsheet component, 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 file into a 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" %} - -### Configure JSON deserialization options - -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 }); -``` - -| Options | Description | -| ----- | ----- | -| onlyValues | If **true**, only the cell values will be loaded. | -| ignoreStyle | If **true**, styles will be excluded when loading the JSON data. | -| ignoreFormula | If **true**, formulas will be excluded when loading the JSON data. | -| ignoreFormat | If **true**, number formats will be excluded when loading the JSON data. | -| ignoreConditionalFormat | If **true**, conditional formatting will be excluded when loading the JSON data. | -| ignoreValidation | If **true**, data validation rules will be excluded when loading the JSON data. | -| ignoreFreezePane | If **true**, freeze panes will be excluded when loading the JSON data. | -| ignoreWrap | If **true**, text wrapping settings will be excluded when loading the JSON data. | -| ignoreChart | If **true**, charts will be excluded when loading the JSON data. | -| ignoreImage | If **true**, images will be excluded when loading the JSON data. | -| ignoreNote | If **true**, notes will be 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" %} - -### Improving Excel file 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)); -} -``` - -### 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. - - -``` - -### Add custom header during open - -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" %} - -### External workbook confirmation dialog - -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]; - 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) - -### Supported file formats - -The following list of Excel file formats are supported in Spreadsheet: - -* Microsoft Excel (.xlsx) -* Microsoft Excel 97-2003 (.xls) -* Comma Separated Values (.csv) -* Excel Macro-Enabled Workbook (.xlsm) -* Excel Binary Workbook(.xlsb) - -## Save - -The Spreadsheet control saves its data, style, format, and more as Excel file document. To enable this feature, set [`allowSave`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#allowsave) as `true` and assign service url to the [`saveUrl`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#saveurl) property. - -**User Interface**: - -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 trigger 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 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 an excel file as blob data - -By default, the Spreadsheet component 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 component 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 an Excel file to a server - -By default, the Spreadsheet component 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) - { - ExcelEngine excelEngine = new ExcelEngine(); - IApplication application = excelEngine.Excel; - try - { - - // Save the workbook as stream. - Stream fileStream = Workbook.Save(saveSettings); - // Using XLSIO, we are opening the file stream and saving the file in the server under "Files" folder. - // You can also save the stream file in your server location. - IWorkbook workbook = application.Workbooks.Open(fileStream); - 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 an excel file using a hosted web service in 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 data as a 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" %} - -### Configure JSON serialization options - -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" %} - -### Send and receive custom params from client to server - -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 header during save - -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" %} - -### Change the PDF 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" %} - -### Supported file formats - -The following list of Excel file formats are supported in Spreadsheet: - -* Microsoft Excel (.xlsx) -* Microsoft Excel 97-2003 (.xls) -* Comma Separated Values (.csv) -* Portable Document Format (.pdf) - -### Methods - -To save the Spreadsheet document as an `xlsx, xls, csv, or pdf` file, by using [save](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#save) method should be called with the `url`, `fileName` and `saveType` as parameters. The following code example shows to save the spreadsheet file as an `xlsx, xls, csv, or pdf` in the button click event. - -{% tabs %} -{% highlight js tabtitle="app.jsx" %} -{% include code-snippet/spreadsheet/react/save-cs1/app/app.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="app.tsx" %} -{% include code-snippet/spreadsheet/react/save-cs1/app/app.tsx %} -{% endhighlight %} -{% highlight js tabtitle="datasource.jsx" %} -{% include code-snippet/spreadsheet/react/save-cs1/app/datasource.jsx %} -{% endhighlight %} -{% highlight ts tabtitle="datasource.tsx" %} -{% include code-snippet/spreadsheet/react/save-cs1/app/datasource.tsx %} -{% endhighlight %} -{% endtabs %} - - {% previewsample "/document-processing/code-snippet/spreadsheet/react/save-cs1" %} - -## Server Configuration - -In Spreadsheet control, Excel import and export support processed in `server-side`, to use importing and exporting in your projects, it is required to create a server with any of the following web services. - -* WebAPI -* WCF Service -* ASP.NET MVC Controller Action - -The following code snippets shows server configuration using `WebAPI` service. - -```csharp - - [Route("api/[controller]")] - public class SpreadsheetController : Controller - { - //To open Excel file - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("Open")] - public IActionResult Open(IFormCollection openRequest) - { - OpenRequest open = new OpenRequest(); - open.File = openRequest.Files[0]; - return Content(Workbook.Open(open)); - } - - //To save as Excel file - [AcceptVerbs("Post")] - [HttpPost] - [EnableCors("AllowAllOrigins")] - [Route("Save")] - public IActionResult Save([FromForm]SaveSettings saveSettings) - { - return Workbook.Save(saveSettings); - } - } -``` - -## Server Dependencies - -Open and save helper functions are shipped in the Syncfusion.EJ2.Spreadsheet package, which is available in Essential Studio® and [`nuget.org`](https://www.nuget.org/). Following list of dependencies required for Spreadsheet open and save operations. - -* Syncfusion.EJ2 -* Syncfusion.EJ2.Spreadsheet -* Syncfusion.Compression.Base -* Syncfusion.XlsIO.Base - -And also refer [this](https://help.syncfusion.com/document-processing/excel/spreadsheet/asp-net-core/open-save#server-dependencies) for more information. - -## Note - -You can refer to our [React Spreadsheet](https://www.syncfusion.com/spreadsheet-editor-sdk/react-spreadsheet-editor) feature tour page for its groundbreaking feature representations. You can also explore our [React Spreadsheet example](https://www.syncfusion.com/spreadsheet-editor-sdk/react-spreadsheet-editor) to knows how to present and manipulate data. - -## See Also - -* [Filtering](./filter) -* [Sorting](./sort) -* [Hyperlink](./link) -* [Docker Image](./docker-deployment) diff --git a/Document-Processing/Excel/Spreadsheet/React/save-excel-files.md b/Document-Processing/Excel/Spreadsheet/React/save-excel-files.md new file mode 100644 index 0000000000..988f2cf95f --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/save-excel-files.md @@ -0,0 +1,458 @@ +--- +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: Open +documentation: ug +--- + +# Save Excel Files in Syncfusion React Spreadsheet + +When exporting an Excel file from the React Spreadsheet component, the process is handled through a streamlined server‑side workflow. 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. + +Once generated, this JSON workbook is sent to the server, where the [`Syncfusion.EJ2.Spreadsheet library`](https://www.nuget.org/packages/Syncfusion.EJ2.Spreadsheet.AspNet.Core) uses [`Syncfusion XlsIO`](https://help.syncfusion.com/document-processing/excel/excel-library/net/overview) to convert the JSON data into a fully formatted Excel file. During this process, the JSON workbook is parsed and its contents are mapped to an XlsIO Workbook instance, ensuring 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. + +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/documentation/api/spreadsheet/index-default#saveurl) property in the Spreadsheet control. You can also use the [`beforeSave`](https://ej2.syncfusion.com/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 ts tabtitle="index.ts" %} +{% include code-snippet/spreadsheet/javascript-es6/open-save-cs5/index.ts %} +{% endhighlight %} +{% highlight html tabtitle="index.html" %} +{% include code-snippet/spreadsheet/javascript-es6/open-save-cs5/index.html %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/javascript-es6/open-save-cs5" %} + +Please find the below table for the [`beforeSave`](https://ej2.syncfusion.com/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/documentation/api/spreadsheet/index-default#allowsave) property is `true`. For demonstration purpose, we have showcased the [allowSave](https://ej2.syncfusion.com/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/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/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/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 ts tabtitle="index.ts" %} +{% include code-snippet/spreadsheet/javascript-es6/save-as-blobdata-cs1/index.ts %} +{% endhighlight %} +{% highlight html tabtitle="index.html" %} +{% include code-snippet/spreadsheet/javascript-es6/save-as-blobdata-cs1/index.html %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/javascript-es6/save-as-blobdata-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/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/documentation/api/spreadsheet/index-default#beforesave) event. After that, convert the spreadsheet data into JSON format using the [saveAsJson](https://ej2.syncfusion.com/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. + +```ts +import { Spreadsheet } from '@syncfusion/ej2-spreadsheet'; + +let saveInitiated: boolean; +//Initialize Spreadsheet component +let spreadsheet: Spreadsheet = new Spreadsheet({ + sheets: [ + ], + saveUrl:'https://xxxxxxxxxxxxxxxxxxxxxxxxx.amazonaws.com/Prod/api/spreadsheet/save', + beforeSave: (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); + }); + }); +}; + +//Render initialized Spreadsheet component +spreadsheet.appendTo('#spreadsheet'); +``` + +```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/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/documentation/api/spreadsheet/index-default#beforesave) event. + +The following code example shows how to save the spreadsheet data as base64 string. + +{% tabs %} +{% highlight ts tabtitle="index.ts" %} +{% include code-snippet/spreadsheet/javascript-es6/base-64-string/index.ts %} +{% endhighlight %} +{% highlight html tabtitle="index.html" %} +{% include code-snippet/spreadsheet/javascript-es6/base-64-string/index.html %} +{% endhighlight %} +{% endtabs %} + +{% previewsample "/document-processing/code-snippet/spreadsheet/javascript-es6/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" %} + + +## Server configuration + +In the Spreadsheet component, Excel export processing is handled on the `server‑side`. Therefore, to enable exporting in your application, you need to configure a server using any of the following web service technologies: + +* WebAPI +* WCF Service +* ASP.NET MVC Controller Action + +The following code snippet shows how to configure the server using a `WebAPI` service: + +```csharp +[Route("api/[controller]")] +public class SpreadsheetController : Controller +{ + // To save as Excel file + [AcceptVerbs("Post")] + [HttpPost] + [EnableCors("AllowAllOrigins")] + [Route("Save")] + public IActionResult Save([FromForm] SaveSettings saveSettings) + { + return Workbook.Save(saveSettings); + } +} +``` + +## Server dependencies + +Save helper functions are included in the `Syncfusion.EJ2.Spreadsheet` package, which is available in Essential Studio® and on [`nuget.org`](https://www.nuget.org). +The following dependencies are required for Spreadsheet save operations: + +* Syncfusion.EJ2 +* Syncfusion.EJ2.Spreadsheet +* Syncfusion.Compression.Base +* Syncfusion.XlsIO.Base diff --git a/Document-Processing/Excel/Spreadsheet/React/server-deployment.md b/Document-Processing/Excel/Spreadsheet/React/server-deployment.md new file mode 100644 index 0000000000..b74d41c69e --- /dev/null +++ b/Document-Processing/Excel/Spreadsheet/React/server-deployment.md @@ -0,0 +1,17 @@ +--- +layout: post +title: Server Deployment Guide for Syncfusion Spreadsheet | Syncfusion +description: Learn here how to deploy the Syncfusion Spreadsheet Server in selected deployment environment of Syncfusion Essential JS 2 and more. +control: Server Deployment +platform: document-processing +documentation: ug +--- + +# Deploying Spreadsheet Server in Selected Deployment Environment + +The Syncfusion React Spreadsheet relies on a server-side application to process Excel files. The server converts Excel files to the Spreadsheet JSON model for rendering in the client and converts the JSON model back to Excel files when saving. This section explains how to deploy the spreadsheet server to user preferred environment and expose stable service URLs for the Spreadsheet to use. + +## See Also + +* [Open](../react/open/open) +* [Save](../react/save/save) \ No newline at end of file