Skip to content

Commit a579e27

Browse files
Merge pull request #2315 from syncfusion-content/EJ2-1011997-dev
1011997: Need to include new UG section for open-save file from Google Drive
2 parents 9eb1d08 + 9ee9517 commit a579e27

3 files changed

Lines changed: 390 additions & 0 deletions

File tree

Document-Processing-toc.html

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5272,13 +5272,15 @@
52725272
<li><a href="/document-processing/excel/spreadsheet/react/open-excel-file/from-aws-s3-bucket">From AWS S3</a></li>
52735273
<li><a href="/document-processing/excel/spreadsheet/react/open-excel-file/from-azure-blob-storage">From Azure Blob Storage</a></li>
52745274
<li><a href="/document-processing/excel/spreadsheet/react/open-excel-file/from-google-cloud-storage">From Google Cloud Storage</a></li>
5275+
<li><a href="/document-processing/excel/spreadsheet/react/open-excel-file/from-google-drive">From Google Drive</a></li>
52755276
</ul>
52765277
</li>
52775278
<li><a href="/document-processing/excel/spreadsheet/react/save-excel-files">Save Excel Files</a>
52785279
<ul>
52795280
<li><a href="/document-processing/excel/spreadsheet/react/save-excel-file/to-aws-s3-bucket">To AWS S3</a></li>
52805281
<li><a href="/document-processing/excel/spreadsheet/react/save-excel-file/to-azure-blob-storage">To Azure Blob Storage</a></li>
52815282
<li><a href="/document-processing/excel/spreadsheet/react/save-excel-file/to-google-cloud-storage">To Google Cloud Storage</a></li>
5283+
<li><a href="/document-processing/excel/spreadsheet/react/save-excel-file/to-google-drive">To Google Drive</a></li>
52825284
</ul>
52835285
</li>
52845286
<li><a href="/document-processing/excel/spreadsheet/react/server-deployment/spreadsheet-server-docker-image-overview">Server Deployment</a>
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
---
2+
layout: post
3+
title: Open excel from Google Drive in React Spreadsheet control | Syncfusion
4+
description: Learn about how to Open an Excel file from Google Drive in React Spreadsheet control of Syncfusion Essential JS 2.
5+
platform: document-processing
6+
control: Open file from Google Drive
7+
documentation: ug
8+
---
9+
10+
# Open file from Google Drive
11+
12+
To load a file from Google Drive in a Spreadsheet Component, you can follow the steps below
13+
14+
**Step 1:** Set up Google Drive API
15+
16+
You must set up a project in the Google Developers Console and enable the Google Drive API. Obtain the necessary credentials to access the API. For more information, view the official [link](https://developers.google.com/workspace/drive/api/guides/enable-sdk).
17+
18+
**Step 2:** Create a Simple Spreadsheet Sample in React
19+
20+
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.
21+
22+
**Step 3:** Modify the `SpreadsheetController.cs` File in the Web Service Project
23+
24+
* 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.
25+
26+
* Open the `SpreadsheetController.cs` file in your web service project.
27+
28+
* Import the required namespaces at the top of the file:
29+
30+
```csharp
31+
32+
using Google.Apis.Auth.OAuth2;
33+
using Google.Apis.Drive.v3;
34+
using Google.Apis.Services;
35+
using Syncfusion.EJ2.Spreadsheet;
36+
37+
```
38+
39+
* 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.
40+
41+
```csharp
42+
43+
//variables for storing GDrive folderId, ApplicationName and Service-Accountkey credentials
44+
public readonly string folderId;
45+
public readonly string applicationName;
46+
public readonly string credentialPath;
47+
48+
//constructor for assigning credentials
49+
public SpreadsheetController(IConfiguration configuration)
50+
{
51+
folderId = configuration.GetValue<string>("FolderId");
52+
credentialPath = configuration.GetValue<string>("CredentialPath");
53+
applicationName = configuration.GetValue<string>("ApplicationName");
54+
}
55+
56+
```
57+
58+
* Create the `OpenExcelFromGoogleDrive()` method to open the document from the Google Drive.
59+
60+
```csharp
61+
62+
[HttpPost]
63+
[Route("OpenExcelFromGoogleDrive")]
64+
public async Task<IActionResult> OpenExcelFromGoogleDrive([FromBody] FileOptions options)
65+
{
66+
try
67+
{
68+
// Create a memory stream to store file data
69+
MemoryStream stream = new MemoryStream();
70+
71+
// Authenticate using Service Account
72+
GoogleCredential credential;
73+
// Load Google service account credentials
74+
using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
75+
{
76+
credential = GoogleCredential.FromStream(streamKey)
77+
.CreateScoped(DriveService.Scope.Drive);
78+
}
79+
80+
// Create Google Drive API service
81+
var service = new DriveService(new BaseClientService.Initializer()
82+
// Initialize Google Drive API client
83+
{
84+
HttpClientInitializer = credential,
85+
ApplicationName = applicationName,
86+
});
87+
88+
// List Excel files in Google Drive folder
89+
var listRequest = service.Files.List();
90+
// Query Google Drive for Excel, CSV files in the specified folder
91+
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";
92+
listRequest.Fields = "files(id, name)";
93+
var files = await listRequest.ExecuteAsync();
94+
// Find the requested file
95+
string fileIdToDownload = files.Files.FirstOrDefault(f => f.Name == options.FileName + options.Extension)?.Id;
96+
// Get the file ID for the requested file name
97+
if (string.IsNullOrEmpty(fileIdToDownload))
98+
// Get the file ID for the requested file name
99+
return NotFound("File not found in Google Drive.");
100+
// Download the file
101+
var request = service.Files.Get(fileIdToDownload);
102+
await request.DownloadAsync(stream);
103+
// Download file content into memory stream
104+
stream.Position = 0;
105+
// Prepare file for Syncfusion Excel processing
106+
OpenRequest open = new OpenRequest
107+
// Wrap downloaded stream as FormFile for Syncfusion processing
108+
{
109+
File = new FormFile(stream, 0, stream.Length, options.FileName, options.FileName + options.Extension)
110+
};
111+
112+
// Convert Excel file to JSON using Syncfusion XlsIO
113+
var result = Workbook.Open(open);
114+
return Content(result, "application/json");
115+
}
116+
catch (Exception ex)
117+
{
118+
return BadRequest("Error occurred while processing the file: " + ex.Message);
119+
}
120+
}
121+
122+
// Class to store FileOptions
123+
public class FileOptions
124+
{
125+
public string FileName { get; set; } = string.Empty;
126+
public string Extension { get; set; } = string.Empty;
127+
}
128+
129+
```
130+
131+
* Open the `appsettings.json` file in your web service project, add your Google Drive configuration details.
132+
133+
```json
134+
135+
{
136+
"Logging": {
137+
"LogLevel": {
138+
"Default": "Information",
139+
"Microsoft.AspNetCore": "Warning"
140+
}
141+
},
142+
"AllowedHosts": "*",
143+
"CredentialPath": "path-to-your-service-account-key.json",
144+
"FolderId": "your-google-drive-folder-id",
145+
"ApplicationName": "YourAppName"
146+
}
147+
148+
```
149+
150+
N> Replace the **credential path**, **folderId** and **application name** in json file with your actual Google drive folder ID , your name for your application and the path for the JSON file.
151+
152+
**Step 4:** Modify the index File in the Spreadsheet sample to make a fetch call to the server to retrieve and process the Excel file from the Google Drive and load the JSON result into the client-side spreadsheet using the [openFromJson](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/index-default#openfromjson) method.
153+
154+
```typescript
155+
<button className="e-btn" onClick={openFromGoogleDrive} style={{ marginLeft: '10px' }}>
156+
Open from Drive
157+
</button>
158+
159+
const openFromGoogleDrive = () => {
160+
spreadsheet.showSpinner();
161+
// Make a POST request to the backend API to open the file from Google Drive.
162+
// Replace the URL with your local or hosted endpoint URL.
163+
fetch('https://localhost:your_port_number/api/spreadsheet/OpenExcelFromGoogleDrive', {
164+
method: 'POST',
165+
headers: {
166+
'Content-Type': 'application/json',
167+
},
168+
body: JSON.stringify({
169+
FileName: fileInfo.name, // Name of the file to open
170+
Extension: fileInfo.extension, // File extension (.xlsx)
171+
}),
172+
})
173+
.then((response) => response.json()) // Parse the response as JSON
174+
.then((data) => {
175+
spreadsheet.hideSpinner();
176+
// Load the spreadsheet data into the UI
177+
spreadsheet.openFromJson({ file: data, triggerEvent: true });
178+
})
179+
.catch((error) => {
180+
spreadsheet.hideSpinner();
181+
window.alert('Error importing file from Google Drive: ' + error);
182+
});
183+
};
184+
```
185+
186+
N> The Google.Apis.Drive.v3 NuGet package must be installed in your application to use the previous code example.
187+
188+
[View sample in GitHub](https://github.com/SyncfusionExamples/syncfusion-react-spreadsheet-google-drive-integration)

0 commit comments

Comments
 (0)