|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: Save excel to Google Drive in React Spreadsheet control | Syncfusion |
| 4 | +description: Learn about how to Save an Excel file from Google Drive in React Spreadsheet control of Syncfusion Essential JS 2. |
| 5 | +platform: document-processing |
| 6 | +control: Save file to Google Drive |
| 7 | +documentation: ug |
| 8 | +--- |
| 9 | + |
| 10 | +# Save file to Google Drive |
| 11 | + |
| 12 | +To save a file to Google Drive in a Spreadsheet Component, you can follow the steps below |
| 13 | + |
| 14 | +**Step 1:** Create a Simple Spreadsheet Sample in React |
| 15 | + |
| 16 | +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. |
| 17 | + |
| 18 | +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project |
| 19 | + |
| 20 | +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. |
| 21 | + |
| 22 | +2. Open the `SpreadsheetController.cs` file in your web service project. |
| 23 | + |
| 24 | +3. Import the required namespaces at the top of the file: |
| 25 | + |
| 26 | +```csharp |
| 27 | + |
| 28 | +using Google.Apis.Auth.OAuth2; |
| 29 | +using Google.Apis.Drive.v3; |
| 30 | +using Google.Apis.Services; |
| 31 | +using Syncfusion.EJ2.Spreadsheet; |
| 32 | + |
| 33 | +``` |
| 34 | + |
| 35 | +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. |
| 36 | + |
| 37 | +```csharp |
| 38 | + |
| 39 | +//variables for storing GDrive folderId, ApplicationName and Service-Accountkey credentials |
| 40 | +public readonly string folderId; |
| 41 | +public readonly string applicationName; |
| 42 | +public readonly string credentialPath; |
| 43 | + |
| 44 | +//constructor for assigning credentials |
| 45 | +public SpreadsheetController(IConfiguration configuration) |
| 46 | +{ |
| 47 | + folderId = configuration.GetValue<string>("FolderId"); |
| 48 | + credentialPath = configuration.GetValue<string>("CredentialPath"); |
| 49 | + applicationName = configuration.GetValue<string>("ApplicationName"); |
| 50 | +} |
| 51 | + |
| 52 | +``` |
| 53 | + |
| 54 | +5. Create the `SaveExcelToGoogleDrive()` method to save the document to the Google Drive. |
| 55 | + |
| 56 | +```csharp |
| 57 | + |
| 58 | +[HttpPost] |
| 59 | +[Route("SaveExcelToGoogleDrive")] |
| 60 | +public async Task<IActionResult> SaveExcelToGoogleDrive([FromForm] SaveSettings saveSettings) |
| 61 | +{ |
| 62 | + try |
| 63 | + { |
| 64 | + //Generate Excel file stream using Syncfusion |
| 65 | + Stream generatedStream = Workbook.Save<Stream>(saveSettings); |
| 66 | + //Copy to MemoryStream to ensure full content is flushed and seekable |
| 67 | + MemoryStream excelStream = new MemoryStream(); |
| 68 | + // Copy generated stream to MemoryStream for upload |
| 69 | + await generatedStream.CopyToAsync(excelStream); |
| 70 | + excelStream.Position = 0; // Reset position for upload |
| 71 | + // Prepare file name with extension based on SaveType |
| 72 | + string fileName = saveSettings.FileName + "." + saveSettings.SaveType.ToString().ToLower(); |
| 73 | + // Validate service account credential file |
| 74 | + if (!System.IO.File.Exists(credentialPath)) |
| 75 | + throw new FileNotFoundException($"Service account key file not found at {credentialPath}"); |
| 76 | + //Authenticate using Service Account credentials |
| 77 | + GoogleCredential credential; |
| 78 | + // Load Google service account credentials |
| 79 | + using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read)) |
| 80 | + { |
| 81 | + credential = GoogleCredential.FromStream(streamKey) |
| 82 | + .CreateScoped(DriveService.Scope.Drive); |
| 83 | + } |
| 84 | + //Initialize Google Drive API service |
| 85 | + var service = new DriveService(new BaseClientService.Initializer() |
| 86 | + // Initialize Google Drive API client |
| 87 | + { |
| 88 | + HttpClientInitializer = credential, |
| 89 | + ApplicationName = applicationName, |
| 90 | + }); |
| 91 | + //Prepare file metadata |
| 92 | + var fileMetadata = new Google.Apis.Drive.v3.Data.File() |
| 93 | + { |
| 94 | + Name = fileName |
| 95 | + }; |
| 96 | + //Check if file already exists in the specified folder |
| 97 | + var listRequest = service.Files.List(); |
| 98 | + listRequest.Q = $"name='{fileName}' and trashed=false"; |
| 99 | + // Query Google Drive for Excel, CSV files in the specified folder |
| 100 | + listRequest.Fields = "files(id)"; |
| 101 | + var files = await listRequest.ExecuteAsync(); |
| 102 | + // Reset stream position before upload (important for both update and create) |
| 103 | + excelStream.Position = 0; |
| 104 | + // Set MIME type dynamically based on SaveType |
| 105 | + string mimeType = saveSettings.SaveType switch |
| 106 | + { |
| 107 | + SaveType.Xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| 108 | + SaveType.Xls => "application/vnd.ms-excel", |
| 109 | + SaveType.Csv => "text/csv", |
| 110 | + }; |
| 111 | + |
| 112 | + if (files.Files.Any()) |
| 113 | + { |
| 114 | + // If File exists Update in the existing file |
| 115 | + var updateRequest = service.Files.Update(fileMetadata, files.Files[0].Id, excelStream, mimeType); |
| 116 | + updateRequest.Fields = "id"; |
| 117 | + await updateRequest.UploadAsync(); |
| 118 | + } |
| 119 | + else |
| 120 | + { |
| 121 | + // If File does not exist, Create new file |
| 122 | + var createRequest = service.Files.Create(fileMetadata, excelStream,mimeType); |
| 123 | + createRequest.Fields = "id"; |
| 124 | + await createRequest.UploadAsync(); |
| 125 | + } |
| 126 | + return Ok("Excel file successfully saved/updated in Google Drive."); |
| 127 | + } |
| 128 | + catch (Exception ex) |
| 129 | + { |
| 130 | + return BadRequest("Error saving file to Google Drive: " + ex.Message); |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +``` |
| 135 | + |
| 136 | +**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 |
| 137 | + |
| 138 | +```js |
| 139 | +<button class="e-btn" onClick={saveToGoogleDrive}> |
| 140 | + Save to Google Drive |
| 141 | +</button>; |
| 142 | + |
| 143 | +// Save the current spreadsheet to Google Drive |
| 144 | +const saveToGoogleDrive = () => { |
| 145 | + // Convert spreadsheet data to JSON |
| 146 | + spreadsheet.saveAsJson().then((json) => { |
| 147 | + const formData = new FormData(); // Append required fields for backend API |
| 148 | + formData.append("FileName", loadedFileInfo.fileName); // File name |
| 149 | + formData.append("SaveType", loadedFileInfo.saveType); // Format type (Xlsx, Xls, Csv) |
| 150 | + formData.append("JSONData", JSON.stringify(json.jsonObject.Workbook)); // Spreadsheet data |
| 151 | + formData.append( |
| 152 | + "PdfLayoutSettings", |
| 153 | + JSON.stringify({ FitSheetOnOnePage: false }), |
| 154 | + ); // PDF settings |
| 155 | + // Make a POST request to the backend API to save the file to Google Drive. |
| 156 | + // Replace the URL with your local or hosted endpoint URL. |
| 157 | + fetch( |
| 158 | + "https://localhost:your_port_number/api/spreadsheet/SaveExcelToGoogleDrive", |
| 159 | + { |
| 160 | + method: "POST", |
| 161 | + body: formData, |
| 162 | + }, |
| 163 | + ) |
| 164 | + .then((response) => { |
| 165 | + if (!response.ok) throw new Error(`Save failed: ${response.status}`); |
| 166 | + window.alert("Workbook saved successfully to Google Drive."); |
| 167 | + }) |
| 168 | + .catch((error) => { |
| 169 | + window.alert("Error saving to Google Drive: " + error); |
| 170 | + }); |
| 171 | + }); |
| 172 | +}; |
| 173 | +``` |
| 174 | + |
| 175 | +N> Note: Install the Google.Apis.Drive.v3 NuGet package in the service project. |
0 commit comments