Skip to content

Commit 902e33c

Browse files
committed
1011997: Need to include new UG section for open-save file from Google Drive
1 parent 28f054a commit 902e33c

1 file changed

Lines changed: 173 additions & 0 deletions

File tree

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
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:** 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 `OpenExcelFromGoogleDrive()` method to open the document from the Google Drive.
55+
56+
```Csharp
57+
58+
[HttpPost]
59+
[Route("OpenExcelFromGoogleDrive")]
60+
public async Task<IActionResult> OpenExcelFromGoogleDrive([FromBody] FileOptions options)
61+
{
62+
try
63+
{
64+
// Create a memory stream to store file data
65+
MemoryStream stream = new MemoryStream();
66+
67+
// Authenticate using Service Account
68+
GoogleCredential credential;
69+
// Load Google service account credentials
70+
using (var streamKey = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
71+
{
72+
credential = GoogleCredential.FromStream(streamKey)
73+
.CreateScoped(DriveService.Scope.Drive);
74+
}
75+
76+
// Create Google Drive API service
77+
var service = new DriveService(new BaseClientService.Initializer()
78+
// Initialize Google Drive API client
79+
{
80+
HttpClientInitializer = credential,
81+
ApplicationName = applicationName,
82+
});
83+
84+
// List Excel files in Google Drive folder
85+
var listRequest = service.Files.List();
86+
// Query Google Drive for Excel, CSV files in the specified folder
87+
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";
88+
listRequest.Fields = "files(id, name)";
89+
var files = await listRequest.ExecuteAsync();
90+
// Find the requested file
91+
string fileIdToDownload = files.Files.FirstOrDefault(f => f.Name == options.FileName + options.Extension)?.Id;
92+
// Get the file ID for the requested file name
93+
if (string.IsNullOrEmpty(fileIdToDownload))
94+
// Get the file ID for the requested file name
95+
return NotFound("File not found in Google Drive.");
96+
// Download the file
97+
var request = service.Files.Get(fileIdToDownload);
98+
await request.DownloadAsync(stream);
99+
// Download file content into memory stream
100+
stream.Position = 0;
101+
// Prepare file for Syncfusion Excel processing
102+
OpenRequest open = new OpenRequest
103+
// Wrap downloaded stream as FormFile for Syncfusion processing
104+
{
105+
File = new FormFile(stream, 0, stream.Length, options.FileName, options.FileName + options.Extension)
106+
};
107+
108+
// Convert Excel file to JSON using Syncfusion XlsIO
109+
var result = Workbook.Open(open);
110+
return Content(result, "application/json");
111+
}
112+
catch (Exception ex)
113+
{
114+
return BadRequest("Error occurred while processing the file: " + ex.Message);
115+
}
116+
}
117+
118+
// Class to store FileOptions
119+
public class FileOptions
120+
{
121+
public string FileName { get; set; } = string.Empty;
122+
public string Extension { get; set; } = string.Empty;
123+
}
124+
125+
```
126+
127+
6. Open the `appsettings.json` file in your web service project, add your Google Drive configuration details.
128+
129+
```Json
130+
131+
{
132+
"CredentialPath": "path-to-your-service-account-key.json",
133+
"FolderId": "your-google-drive-folder-id",
134+
"ApplicationName": "YourAppName"
135+
}
136+
137+
```
138+
139+
N> Note: Install the Google.Apis.Drive.v3 NuGet package in the service project.
140+
141+
**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 Drive into the client-side spreadsheet.
142+
143+
```typescript
144+
<button className="e-btn" onClick={openFromGoogleDrive} style={{ marginLeft: '10px' }}>
145+
Open from Drive
146+
</button>
147+
148+
const openFromGoogleDrive = () => {
149+
spreadsheet.showSpinner();
150+
// Make a POST request to the backend API to open the file from Google Drive.
151+
// Replace the URL with your local or hosted endpoint URL.
152+
fetch('https://localhost:your_port_number/api/spreadsheet/OpenExcelFromGoogleDrive', {
153+
method: 'POST',
154+
headers: {
155+
'Content-Type': 'application/json',
156+
},
157+
body: JSON.stringify({
158+
FileName: fileInfo.name, // Name of the file to open
159+
Extension: fileInfo.extension, // File extension (.xlsx)
160+
}),
161+
})
162+
.then((response) => response.json()) // Parse the response as JSON
163+
.then((data) => {
164+
spreadsheet.hideSpinner();
165+
// Load the spreadsheet data into the UI
166+
spreadsheet.openFromJson({ file: data, triggerEvent: true });
167+
})
168+
.catch((error) => {
169+
spreadsheet.hideSpinner();
170+
window.alert('Error importing file from Google Drive: ' + error);
171+
});
172+
};
173+
```

0 commit comments

Comments
 (0)