Skip to content

Instantly share code, notes, and snippets.

@shemogumbe
Last active August 22, 2024 15:58
Show Gist options
  • Save shemogumbe/8fdeb761aa63fd2f002b83aae12f2552 to your computer and use it in GitHub Desktop.
Save shemogumbe/8fdeb761aa63fd2f002b83aae12f2552 to your computer and use it in GitHub Desktop.
Get excel worbook data
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
using DotNetEnv;
using System.Reflection;
using Microsoft.Graph.Models;
class Program
{
static async Task Main(string[] args)
{
// Load environment variables from .env file
Env.Load();
var tenantId = Environment.GetEnvironmentVariable("tenant_id");
var clientId = Environment.GetEnvironmentVariable("client_id");
var clientSecret = Environment.GetEnvironmentVariable("client_secret");
if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
{
Console.WriteLine("Please ensure tenant_id, client_id, and client_secret are set in the .env file.");
return;
}
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Initialize the ClientSecretCredential
var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Initialize the GraphServiceClient
var graphClient = new GraphServiceClient(credential, scopes);
Console.WriteLine("Graph Client Initialized");
await GetDriveItem(graphClient);
}
static async Task GetDriveItem(GraphServiceClient graphClient)
{
try
{
// Retrieve the drive item
var driveItem = await graphClient.Drives["<drive-id>"]
.Items["<drive-iem-id-for the-workbook>"]
.Workbook.Worksheets["Project One"]
.GetAsync();
Console.WriteLine($"Drive item name: {driveItem.Name}");
Console.WriteLine($"Tables: {driveItem.Id}");
Console.WriteLine($"Drive item workbook: {driveItem}");
// foreach (var item in driveItem.Value)
// {
// Console.WriteLine($"Item ID: {item.Id}");
// Console.WriteLine($"Item Name: {item.Name}");
// }
}
catch (ServiceException e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment