|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: Opening excel from AWS S3 in React Spreadsheet control | Syncfusion |
| 4 | +description: Learn about how to Open an Excel file from AWS S3 in React Spreadsheet control of Syncfusion Essential JS 2 and more details. |
| 5 | +platform: React |
| 6 | +control: Open file from AWS S3 |
| 7 | +documentation: ug |
| 8 | +--- |
| 9 | + |
| 10 | +# Open file from AWS S3 |
| 11 | + |
| 12 | +To load a file from AWS S3 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](../../React//getting-started.md) 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](../../../Spreadsheet/React/open-save.md) 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 Amazon; |
| 29 | +using Amazon.Runtime; |
| 30 | +using Amazon.S3; |
| 31 | +using Amazon.S3.Model; |
| 32 | +using Amazon.S3.Transfer; |
| 33 | + |
| 34 | +``` |
| 35 | + |
| 36 | +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. |
| 37 | + |
| 38 | +```csharp |
| 39 | + |
| 40 | +private IConfiguration _configuration; |
| 41 | +public readonly string _accessKey; |
| 42 | +public readonly string _secretKey; |
| 43 | +public readonly string _bucketName; |
| 44 | + |
| 45 | +public SpreadsheetController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration) |
| 46 | +{ |
| 47 | + _hostingEnvironment = hostingEnvironment; |
| 48 | + _cache = cache; |
| 49 | + _configuration = configuration; |
| 50 | + _accessKey = _configuration.GetValue<string>("AccessKey"); |
| 51 | + _secretKey = _configuration.GetValue<string>("SecretKey"); |
| 52 | + _bucketName = _configuration.GetValue<string>("BucketName"); |
| 53 | +} |
| 54 | + |
| 55 | +``` |
| 56 | + |
| 57 | +5. Create the `OpenFromS3()` method to open the document from the AWS S3 bucket. |
| 58 | + |
| 59 | +```csharp |
| 60 | + |
| 61 | +[Route("api/[controller]")] |
| 62 | +[ApiController] |
| 63 | +public class SpreadsheetController : ControllerBase |
| 64 | +{ |
| 65 | + [HttpPost] |
| 66 | + [Route("OpenFromS3")] |
| 67 | + public async Task<IActionResult> OpenFromS3([FromBody] FileOptions options) |
| 68 | + { |
| 69 | + try |
| 70 | + { |
| 71 | + //Set AWS region and credentials |
| 72 | + var region = RegionEndpoint.USEast1; |
| 73 | + var config = new AmazonS3Config { RegionEndpoint = region }; |
| 74 | + var credentials = new BasicAWSCredentials("your-access-key", "your-secretkey"); |
| 75 | + //Create an S3 client to interact with AWS |
| 76 | + using (var client = new AmazonS3Client(credentials, config)) |
| 77 | + { |
| 78 | + using (MemoryStream stream = new MemoryStream()) |
| 79 | + { |
| 80 | + //Get the full file name using input from the client |
| 81 | + string bucketName = "your-bucket-name"; |
| 82 | + string fileName = options.FileName + options.Extension; |
| 83 | + //Download the file from S3 into memory |
| 84 | + var response = await client.GetObjectAsync(new GetObjectRequest |
| 85 | + { |
| 86 | + BucketName = bucketName, |
| 87 | + Key = fileName |
| 88 | + }); |
| 89 | + await response.ResponseStream.CopyToAsync(stream); |
| 90 | + stream.Position = 0; // Reset stream position for reading |
| 91 | + //Wrap the stream as a FormFile for processing |
| 92 | + OpenRequest open = new OpenRequest |
| 93 | + { |
| 94 | + File = new FormFile(stream, 0, stream.Length, options.FileName, fileName) |
| 95 | + }; |
| 96 | + //Convert Excel file to JSON using Workbook.Open method. |
| 97 | + var result = Workbook.Open(open); |
| 98 | + //Return the JSON result to the client |
| 99 | + return Content(result, "application/json"); |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + catch (Exception ex) |
| 104 | + { |
| 105 | + // Handle any errors and return a message |
| 106 | + Console.WriteLine($"Error: {ex.Message}"); |
| 107 | + return Content("Error occurred while processing the file."); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + // To receive file details from the client. |
| 112 | + public class FileOptions |
| 113 | + { |
| 114 | + public string FileName { get; set; } = string.Empty; |
| 115 | + public string Extension { get; set; } = string.Empty; |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +``` |
| 120 | + |
| 121 | +6. Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration. |
| 122 | + |
| 123 | +```json |
| 124 | + |
| 125 | +{ |
| 126 | + "Logging": { |
| 127 | + "LogLevel": { |
| 128 | + "Default": "Information", |
| 129 | + "Microsoft.AspNetCore": "Warning" |
| 130 | + } |
| 131 | + }, |
| 132 | + "AllowedHosts": "*", |
| 133 | + "AccessKey": "Your Access Key from AWS S3", |
| 134 | + "SecretKey": "Your Secret Key from AWS S3", |
| 135 | + "BucketName": "Your Bucket name from AWS S3" |
| 136 | +} |
| 137 | + |
| 138 | +``` |
| 139 | + |
| 140 | +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. |
| 141 | + |
| 142 | +**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. |
| 143 | + |
| 144 | +```typescript |
| 145 | + |
| 146 | +<button class="e-btn" (click)="openFromS3()">Import XLS files from AWS S3 bucket</button> |
| 147 | + |
| 148 | +// Function to open a spreadsheet file from AWS S3 via an API call |
| 149 | +const openFromS3 = () => { |
| 150 | + spreadsheet.showSpinner(); |
| 151 | + // Make a POST request to the backend API to fetch the file from S3. Replace the URL with your local or hosted endpoint URL. |
| 152 | + fetch('https://localhost:portNumber/api/spreadsheet/OpenFromS3', { |
| 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 |
| 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 | + // Log any errors that occur during the fetch operation |
| 170 | + window.alert('Error importing file:', error); |
| 171 | + }); |
| 172 | +}; |
| 173 | + |
| 174 | +``` |
| 175 | + |
| 176 | +N> The **AWSSDK.S3** NuGet package must be installed in your application to use the previous code example. |
| 177 | + |
| 178 | +# Save spreadsheet to AWS S3 |
| 179 | + |
| 180 | +To save a file to the AWS S3, you can follow the steps below |
| 181 | + |
| 182 | +**Step 1:** Create a Simple Spreadsheet Sample in React |
| 183 | + |
| 184 | +Start by following the steps provided in this [link](../../React//getting-started.md) to create a simple Spreadsheet sample in React. This will give you a basic setup of the Spreadsheet component. |
| 185 | + |
| 186 | +**Step 2:** Modify the `SpreadsheetController.cs` File in the Web Service Project |
| 187 | + |
| 188 | +1. Create a web service project in .NET Core 3.0 or above. You can refer to this [link](../../../Spreadsheet/React/open-save.md) for instructions on how to create a web service project. |
| 189 | + |
| 190 | +2. Open the `SpreadsheetController.cs` file in your web service project. |
| 191 | + |
| 192 | +3. Import the required namespaces at the top of the file: |
| 193 | + |
| 194 | +```csharp |
| 195 | + |
| 196 | +using Amazon; |
| 197 | +using Amazon.Runtime; |
| 198 | +using Amazon.S3; |
| 199 | +using Amazon.S3.Model; |
| 200 | +using Amazon.S3.Transfer; |
| 201 | + |
| 202 | +``` |
| 203 | + |
| 204 | +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. |
| 205 | + |
| 206 | +```csharp |
| 207 | + |
| 208 | +private IConfiguration _configuration; |
| 209 | +public readonly string _accessKey; |
| 210 | +public readonly string _secretKey; |
| 211 | +public readonly string _bucketName; |
| 212 | + |
| 213 | +public SpreadsheetController(IWebHostEnvironment hostingEnvironment, IMemoryCache cache, IConfiguration configuration) |
| 214 | +{ |
| 215 | + _hostingEnvironment = hostingEnvironment; |
| 216 | + _cache = cache; |
| 217 | + _configuration = configuration; |
| 218 | + _accessKey = _configuration.GetValue<string>("AccessKey"); |
| 219 | + _secretKey = _configuration.GetValue<string>("SecretKey"); |
| 220 | + _bucketName = _configuration.GetValue<string>("BucketName"); |
| 221 | +} |
| 222 | + |
| 223 | +``` |
| 224 | + |
| 225 | +5. Create the `SaveToS3()` method to open the document from the AWS S3 bucket. |
| 226 | + |
| 227 | +```csharp |
| 228 | + |
| 229 | +[HttpPost] |
| 230 | +[Route("SaveToS3")] |
| 231 | +public async Task<IActionResult> SaveToS3([FromForm] SaveSettings saveSettings) |
| 232 | +{ |
| 233 | + try |
| 234 | + { |
| 235 | + // Convert spreadsheet JSON to Excel file stream |
| 236 | + Stream fileStream = Workbook.Save<Stream>(saveSettings); |
| 237 | + fileStream.Position = 0; // Reset stream for upload |
| 238 | +
|
| 239 | + // Set AWS region and credentials |
| 240 | + var region = RegionEndpoint.USEast1; |
| 241 | + var config = new AmazonS3Config { RegionEndpoint = region }; |
| 242 | + var credentials = new BasicAWSCredentials("your-access-key", "your-secretkey"); |
| 243 | + |
| 244 | + // Define S3 bucket and file name |
| 245 | + string bucketName = "your-bucket-name"; |
| 246 | + string fileName = saveSettings.FileName + "." + saveSettings.SaveType.ToString().ToLower(); |
| 247 | + |
| 248 | + // Initialize S3 client |
| 249 | + using (var client = new AmazonS3Client(credentials, config)) |
| 250 | + { |
| 251 | + // Use TransferUtility to upload the file stream |
| 252 | + var fileTransferUtility = new TransferUtility(client); |
| 253 | + await fileTransferUtility.UploadAsync(fileStream, bucketName, fileName); |
| 254 | + } |
| 255 | + |
| 256 | + // Return success message |
| 257 | + return Ok("Excel file successfully saved to AWS S3."); |
| 258 | + } |
| 259 | + catch (Exception ex) |
| 260 | + { |
| 261 | + } |
| 262 | +} |
| 263 | + |
| 264 | +``` |
| 265 | + |
| 266 | +6. Open the `appsettings.json` file in your web service project, Add the following lines below the existing `"AllowedHosts"` configuration. |
| 267 | + |
| 268 | +```json |
| 269 | + |
| 270 | +{ |
| 271 | + "Logging": { |
| 272 | + "LogLevel": { |
| 273 | + "Default": "Information", |
| 274 | + "Microsoft.AspNetCore": "Warning" |
| 275 | + } |
| 276 | + }, |
| 277 | + "AllowedHosts": "*", |
| 278 | + "AccessKey": "Your Access Key from AWS S3", |
| 279 | + "SecretKey": "Your Secret Key from AWS S3", |
| 280 | + "BucketName": "Your Bucket name from AWS S3" |
| 281 | +} |
| 282 | + |
| 283 | +``` |
| 284 | + |
| 285 | +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. |
| 286 | + |
| 287 | +**Step 3:** Modify the index File in the Spreadsheet sample to using [`saveAsJson`](https://ej2.syncfusion.com/react/documentation/api/spreadsheet/#saveasjson) method to serialize the spreadsheet and send it to the backend. |
| 288 | + |
| 289 | +```tsx |
| 290 | + |
| 291 | +// Function to save the current spreadsheet to AWS S3 via an API call |
| 292 | +const saveToS3 = () => { |
| 293 | + // Convert the current spreadsheet to JSON format |
| 294 | + spreadsheet.saveAsJson().then((json) => { |
| 295 | + const formData = new FormData(); |
| 296 | + |
| 297 | + // Append necessary data to the form for the API request |
| 298 | + formData.append('FileName', loadedFileInfo.fileName); // Name of the file to save |
| 299 | + formData.append('saveType', loadedFileInfo.saveType); // Save type |
| 300 | + formData.append('JSONData', JSON.stringify(json.jsonObject.Workbook)); // Spreadsheet data |
| 301 | + formData.append( |
| 302 | + 'PdfLayoutSettings', |
| 303 | + JSON.stringify({ FitSheetOnOnePage: false }) // PDF layout settings |
| 304 | + ); |
| 305 | + |
| 306 | + // Make a POST request to the backend API to save the file to S3. Replace the URL with your local or hosted endpoint URL. |
| 307 | + fetch('https://localhost:portNumber/api/spreadsheet/SaveToS3', { |
| 308 | + method: 'POST', |
| 309 | + body: formData, |
| 310 | + }) |
| 311 | + .then((response) => { |
| 312 | + // Check if the response is successful |
| 313 | + if (!response.ok) { |
| 314 | + throw new Error( |
| 315 | + `Save request failed with status ${response.status}` |
| 316 | + ); |
| 317 | + } |
| 318 | + window.alert('Workbook saved successfully.'); |
| 319 | + }) |
| 320 | + .catch((error) => { |
| 321 | + // Log any errors that occur during the save operation |
| 322 | + window.alert('Error saving to server:', error); |
| 323 | + }); |
| 324 | + }); |
| 325 | +}; |
| 326 | + |
| 327 | +``` |
| 328 | + |
| 329 | +N> The **AWSSDK.S3** NuGet package must be installed in your application to use the previous code example. |
0 commit comments