How to Integrate Google Drive with the Syncfusion React Spreadsheet

Summarize this blog post with:

TL;DR: Stop wasting time with downloads and uploads for even the smallest Excel edit. By integrating Google Drive with Syncfusion React Spreadsheet, developers can let users open, edit, and save files directly inside a React app. This approach eliminates version conflicts, streamlines workflows, and ensures enterprise grade security with backend APIs like openFromJson and saveAsJson. The result is a scalable, cloud native Excel editor that delivers faster performance, better UX, and compliance ready data handling.

Transform your React app into a cloud Excel editor

Modern web applications are increasingly cloud-first. Developers are expected to deliver experiences where users can work with files stored in cloud storage services like Docker, AWS, and Google Drive without downloading, re-uploading, or switching tabs.

In this guide, you’ll learn how to integrate Google Drive with Syncfusion React Spreadsheet, allowing users to open, edit, and save Excel files directly inside a React app using an ASP.NET Core backend. The result is a secure, high-performance, cloud-based Excel editor built for real-world enterprise apps.

Enjoy a smooth experience with Syncfusion’s Excel Library! Get started with a few lines of code and without Microsoft or interop dependencies.

Why Google Drive integration with Syncfusion React Spreadsheet matters

Google Drive is widely used for storing business-critical spreadsheets, financial reports, inventory lists, CRM exports, and operational data.

However, most applications force users to download files just to make small edits. This approach leads to:

  • Poor user experience.
  • Version conflicts.
  • Security risks.
  • Slower workflows.

By integrating Google Drive with Syncfusion React Spreadsheet, you can:

  • Eliminate file downloads and manual uploads.
  • Keep users inside your application.
  • Enable real-time, Excel-like editing in the browser.
  • Maintain enterprise-grade security and performance.

Why choose Syncfusion React Spreadsheet?

The Syncfusion React Spreadsheet component is designed for cloud and enterprise scenarios.

Its key capabilities include:

  • Built-in open and save APIs for backend-driven workflows.
  • Server-side processing for better performance and security.
  • Broad file format support: XLSX, XLS, CSV, XLSM, XLSB, and PDF.
  • Rich Excel-like UI with ribbon, dialogs, formulas, and keyboard shortcuts.
  • Optimized performance for large datasets and complex workbooks.

Combining Syncfusion React Spreadsheet with Google Drive creates a true cloud-based Excel editing experience.

Transform your app into a cloud-based Excel editor with Syncfusion and Google Drive integration

Managing Excel files in Google Drive is now simple and intuitive. With the Syncfusion React Spreadsheet and Google Drive API integration, you can open and save Excel files directly from the cloud, turning your app into a secure, cloud-based Excel editor without the usual complexity.

Open

  • Direct cloud access: Seamlessly load Excel files from Google Drive using your backend API.
  • Flexible file sources: Open files from local uploads, external URLs, blob data, Base64 strings, or server endpoints, ideal for cloud-based workflows.
  • Smart workbook restoration: Use the openFromJson method to bring back full workbook structure, styles, and formulas.
  • Custom logic hooks: Add validations or actions with beforeOpen and openComplete events.
  • Broad format support: Works with .xlsx, .xls, .xlsm, .xlsb, and .csv formats.

Save

  • Secure cloud saving: Send updated spreadsheets back to Google Drive via authenticated API calls.
  • Efficient data handling: Convert workbooks to JSON using the saveAsJson method for backend processing.
  • Excel file generation: Backend transforms JSON into Excel streams using Syncfusion libraries.
  • Event-driven customization: Use beforeSave and saveComplete methods to log actions or apply validations.
  • Export to PDF: Export spreadsheets as PDFs with layout options.

Ready to get started? Here’s what you need before we jump into the integration steps.

Prerequisites

  • Frontend: A React application with Syncfusion React Spreadsheet installed. Follow the Getting started with React Spreadsheet guide to set up your project.
  • Backend: An ASP.NET Core Web API for handling open and save operations. Refer to the Web API repository for setup.
  • Install required NuGet Packages:
    Install-Package Google.Apis.Drive.v3
  • Google Drive API: Enable the Google Drive API and configure service account authentication for secure file access.
  • Configure Google Cloud and Google Drive credentials:
  • Open your appsettings.json file and add your Google Drive configuration details. This should include the service account credential file path, the Google Drive folder ID, and the app name created in the Google developers console (Project Name).Refer to the following code example.
    "CredentialPath": "path-to-your-service-account-key.json",
     "FolderId": "your-google-drive-folder-id",
     "ApplicationName": "YourAppName"

Got everything set up? Let’s move on and make your app a cloud-powered Excel editor!

Step-by-Step guide: Open and save Excel Files from Google Drive in Syncfusion React Spreadsheet

Need to bring Excel files from Google Drive into your React app? Here’s how to do it in just two steps:

Handle Excel files like a pro with Syncfusion’s C# Excel Library, offering well-documented APIs for each functionality.

Opening Excel files from Google Drive to React Spreadsheet

Step 1: Fetch and convert the Excel file

Retrieve the Excel file from Google Drive using the API and convert it to Workbook JSON for Syncfusion React Spreadsheet using the following code snippet.

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Spreadsheet;

namespace WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SpreadsheetController : ControllerBase
    {
        //variables for storing GDrive folderId, ApplicationName, and Service-Accountkey credentials
        public readonly string folderId;
        public readonly string applicationName;
        public readonly string credentialPath;

        //constructor for assigning credentials
        public SpreadsheetController(IConfiguration configuration)
        {
            folderId = configuration.GetValue<string>("FolderId");
            credentialPath = configuration.GetValue<string>("CredentialPath");
            applicationName = configuration.GetValue<string>("ApplicationName");
        }


        [HttpPost]
        [Route("OpenExcelFromGoogleDrive")]
        public async Task<IActionResult> OpenExcelFromGoogleDrive([FromBody] FileOptions options)
        {
            try
            {
                // Create a memory stream to store file data
                MemoryStream stream = new MemoryStream();

                // Authenticate using Service Account
                GoogleCredential credential;

                // Load Google service account credentials
                using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(streamKey)
                        .CreateScoped(DriveService.Scope.Drive);
                }

                // Create Google Drive API service
                var service = new DriveService(new BaseClientService.Initializer()

                // Initialize Google Drive API client
                {
                    HttpClientInitializer = credential,
                    ApplicationName = applicationName,
                });

                // List Excel files in Google Drive folder
                var listRequest = service.Files.List();

                // Query Google Drive for Excel, CSV files in the specified folder
                listRequest.Q = $"(mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' or mimeType='application/vnd.ms-excel' or mimeType='text/csv') and '{folderId}' in parents and trashed=false";
                listRequest.Fields = "files(id, name)";
                var files = await listRequest.ExecuteAsync();
                // Find the requested file
                string fileIdToDownload = files.Files.FirstOrDefault(f => f.Name == options.FileName + options.Extension)?.Id;

                // Get the file ID for the requested file name
                if (string.IsNullOrEmpty(fileIdToDownload))

                    // Get the file ID for the requested file name
                    return NotFound("File not found in Google Drive.");

                    // Download file content into memory stream
                var request = service.Files.Get(fileIdToDownload);
                await request.DownloadAsync(stream);
                stream.Position = 0;

                // Prepare file for Syncfusion Excel processing
                OpenRequest open = new OpenRequest

                // Wrap downloaded stream as FormFile for Syncfusion processing
                {
                    File = new FormFile(stream, 0, stream.Length, options.FileName, options.FileName + options.Extension)
                };

                // Convert Excel file to JSON using Syncfusion XlsIO
                var result = Workbook.Open(open);
                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return BadRequest("Error occurred while processing the file: " + ex.Message);
            }
        }

        // Class to store FileOptions
        public class FileOptions
        {
            public string FileName { get; set; } = string.Empty;
            public string Extension { get; set; } = string.Empty;
        }
}
}

Step 2: Load the file in React

Now, call your backend and use the openFromJson method to display the file in the React Spreadsheet component.

const openFromGoogleDrive = () => {
        spreadsheet.showSpinner();

        // Make a POST request to the backend API to open the file from Google Drive.

        // Replace the URL with your local or hosted endpoint URL.
             fetch('https://localhost:your_port_number/api/spreadsheet/OpenExcelFromGoogleDrive', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                FileName: fileInfo.name,       // Name of the file to open
                Extension: fileInfo.extension, // File extension (.xlsx)
            }),
        })
            .then((response) => response.json()) // Parse the response as JSON
            .then((data) => {
                spreadsheet.hideSpinner();
                // Load the spreadsheet data into the UI
                spreadsheet.openFromJson({ file: data, triggerEvent: true });
            })
            .catch((error) => {
                spreadsheet.hideSpinner();
                window.alert('Error importing file from Google Drive: ' + error);

            }); };

Witness the possibilities in demos showcasing the robust features of Syncfusion’s C# Excel Library.

Save edited Excel files in React Spreadsheet to Google Drive

Once your edits are done, push them to Google Drive to keep everything backed up and accessible in the cloud.

Step 1: Convert Spreadsheet to JSON

Use the saveAsJson method to serialize the React Spreadsheet and send it to the backend.

// Save the current spreadsheet to Google Drive
    const saveToGoogleDrive = () => {
        // Convert spreadsheet data to JSON
        spreadsheet.saveAsJson().then((json) => {
            const formData = new FormData();

            // Append required fields for backend API
            formData.append('FileName', loadedFileInfo.fileName);   // File name
            formData.append('SaveType', loadedFileInfo.saveType);   // Format type (Xlsx, Xls, Csv)
            formData.append('JSONData', JSON.stringify(json.jsonObject.Workbook)); // Spreadsheet data
            formData.append('PdfLayoutSettings', JSON.stringify({ FitSheetOnOnePage: false })); // PDF settings

            // Make a POST request to the backend API to save the file to Google Drive.

            // Replace the URL with your local or hosted endpoint URL.
            fetch('https://localhost:your_port_number/api/spreadsheet/SaveExcelToGoogleDrive', {
                method: 'POST',
                body: formData,
            })
                .then((response) => {
                    if (!response.ok) throw new Error(`Save failed: ${response.status}`);
                    window.alert('Workbook saved successfully to Google Drive.');
                })
                .catch((error) => {
                    window.alert('Error saving to Google Drive: ' + error);
                });
        });
    };

Step 2: Convert and upload to Google Drive

Then convert the JSON to Excel on the server and securely upload it to Google Drive.

Here’s the code snippet to implement this feature in your app.

[HttpPost]
[Route("SaveExcelToGoogleDrive")]
public async Task<IActionResult> SaveExcelToGoogleDrive([FromForm] SaveSettings saveSettings)
{
    try
    {
         //Generate Excel file stream using Syncfusion
        Stream generatedStream = Workbook.Save<Stream>(saveSettings);

        //Copy to MemoryStream to ensure full content is flushed and seekable
        MemoryStream excelStream = new MemoryStream();

        // Copy generated stream to MemoryStream for upload
        await generatedStream.CopyToAsync(excelStream);
        excelStream.Position = 0; // Reset position for upload

        // Prepare file name with extension based on SaveType
        string fileName = saveSettings.FileName + "." + saveSettings.SaveType.ToString().ToLower();

        // Validate service account credential file
        if (!System.IO.File.Exists(credentialPath))
            throw new FileNotFoundException($"Service account key file not found at {credentialPath}");

        //Authenticate using Service Account credentials
        GoogleCredential credential;

        // Load Google service account credentials
        using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(streamKey)
                .CreateScoped(DriveService.Scope.Drive);
        }

        //Initialize Google Drive API service
        var service = new DriveService(new BaseClientService.Initializer()

        // Initialize Google Drive API client
        {
            HttpClientInitializer = credential,
            ApplicationName = applicationName,
        });

        //Prepare file metadata
        var fileMetadata = new Google.Apis.Drive.v3.Data.File()
        {
            Name = fileName
        };

        //Check if file already exists in the specified folder
        var listRequest = service.Files.List();
        listRequest.Q = $"name='{fileName}' and trashed=false";

        // Query Google Drive for Excel, CSV files in the specified folder
        listRequest.Fields = "files(id)";
        var files = await listRequest.ExecuteAsync();

        // Reset stream position before upload (important for both update and create)
        excelStream.Position = 0;

        // Set MIME type dynamically based on SaveType
         string mimeType = saveSettings.SaveType switch
         {
            SaveType.Xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            SaveType.Xls => "application/vnd.ms-excel",
            SaveType.Csv => "text/csv",
         };

        if (files.Files.Any())
        {
            // If file exists, update the existing file
            var updateRequest = service.Files.Update(fileMetadata, files.Files[0].Id, excelStream,
                mimeType);
            updateRequest.Fields = "id";
            await updateRequest.UploadAsync();
        }
        else
        {

            // If file does not exist, create a new file
            var createRequest = service.Files.Create(fileMetadata, excelStream,mimeType);
            createRequest.Fields = "id";
            await createRequest.UploadAsync();
        }

        return Ok("Excel file successfully saved/updated in Google Drive.");
    }
    catch (Exception ex)
    {
        return BadRequest("Error saving file to Google Drive: " + ex.Message);
    }
}

After executing the above code examples, we will get an output that resembles the following GIF.

Integrating Google Drive with Syncfusion React Spreadsheet to work with Excel files
Integrating Google Drive with Syncfusion React Spreadsheet to work with Excel files

GitHub reference

Also, refer to the integrating Google Drive with React Spreadsheet GitHub demo, featuring:

  • React client sample
    A ready-to-use frontend showcasing Syncfusion React Spreadsheet integrated with Google Drive for opening and saving Excel files.
  • ASP.NET Core Web API backend
    A secure backend service that handles file operations with Google Drive using service account authentication and the Drive API.

Frequently Asked Questions

What is the main purpose of integrating Google Drive with Syncfusion React Spreadsheet?

The integration enables users to open, edit, and save Excel files directly from Google Drive within a React application, eliminating the need for file downloads or switching between platforms.

What file formats are supported when working with Google Drive integration?

The solution supports common formats such as Excel (XLSX, XLS), CSV, and even allows exporting files to PDF.
References: Open and Save.

How does the application open files from Google Drive?

The backend retrieves the file from Google Drive, converts it into Spreadsheet-compatible JSON, and loads it into the React Spreadsheet.
Reference: Open file from Google Drive.

How are edited spreadsheets saved back to Google Drive?

The client serializes the spreadsheet data to JSON and sends it to the backend, where it is converted into an Excel stream and uploaded to Google Drive.
Reference: Save file to Google Drive.

Why is a backend required for Google Drive integration?

The backend handles secure authentication, file retrieval, conversion, and upload operations, keeping Google Drive credentials and processing logic off the client.

What prerequisites are required to implement this integration?

A React app with Syncfusion Spreadsheet, an ASP.NET Core Web API backend, Google Drive API access, and configured service account credentials.

Can this integration handle large Excel files efficiently?

Yes. Syncfusion Spreadsheet is optimized for performance and server-side processing, making it suitable for larger datasets.
Reference: Advanced Open options.

Can this solution be used to build enterprise-grade applications?

Absolutely. The integration is scalable, secure, and designed to meet enterprise requirements, making it suitable for complex business applications.

What makes this solution a “cloud-based Excel editor”?

Since users can directly access, edit, and save files from cloud storage without local downloads, the application effectively functions as a full-featured cloud Excel editor.

Can this integration work with other cloud storage providers?

Yes. Similar integration patterns can be applied to other storage services, such as AWS S3, Azure Blob Storage, and Google Cloud Storage.

Syncfusion’s high-performance PDF Library allows you to create PDF documents from scratch without Adobe dependencies.

Build cloud‑connected Excel experiences with Syncfusion React Spreadsheet

Thanks for reading! Integrating Google Drive with Syncfusion React Spreadsheet Editor delivers a seamless, cloud-based Excel experience that simplifies file access, editing, and secure saving. This scalable approach is well-suited for modern web apps that require efficient data workflows and real-time collaboration. By combining powerful spreadsheet functionality with trusted cloud storage, developers can build smarter, more responsive solutions with confidence.

Try Syncfusion Spreadsheet today and start building intelligent spreadsheet solutions in your React app!

If you’re a Syncfusion user, you can download the setup from the license and downloads page. Otherwise, you can download a free 30-day trial.

You can also contact us through our support forumsupport portal, or feedback portal for queries. We are always happy to assist you!

 

Be the first to get updates

Sastha PrathapSastha Prathap profile icon

Meet the Author

Sastha Prathap

Sastha Prathap joined Syncfusion in 2015. He manages the Syncfusion Pivot Table component. He derives great satisfaction from writing code and employs his skills with unwavering passion.

Leave a comment