-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
71 lines (59 loc) · 2.48 KB
/
Program.cs
File metadata and controls
71 lines (59 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using System.Net.Http.Json;
// Models
public class WeatherForecast
{
public HourlyData Hourly { get; set; }
}
public class HourlyData
{
public List<string> Time { get; set; }
public List<double> Temperature_2m { get; set; }
}
class Program
{
static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
static readonly string ApplicationName = "CSharp Weather to Google Sheets";
static readonly string SpreadsheetId = "1woc9K7LrfSoTcaby_f__NyTjBPpIaps6LwQHqOXU5Gw"; // your ID
static readonly string SheetName = "WorkSheet1";
static async Task Main()
{
// --- Step 1: Fetch weather data ---
using HttpClient client = new();
string apiUrl = "https://api.open-meteo.com/v1/forecast?latitude=22.28&longitude=114.17&hourly=temperature_2m";
var forecast = await client.GetFromJsonAsync<WeatherForecast>(apiUrl);
if (forecast == null || forecast.Hourly?.Time == null)
{
Console.WriteLine("No data retrieved from Open-Meteo.");
return;
}
// --- Step 2: Prepare rows for Sheets ---
var values = new List<IList<object>>();
values.Add(new List<object> { "Time", "Temperature (°C)" }); // Header row
for (int i = 0; i < forecast.Hourly.Time.Count; i++)
{
values.Add(new List<object> {
forecast.Hourly.Time[i],
forecast.Hourly.Temperature_2m[i]
});
}
// --- Step 3: Connect to Google Sheets ---
using var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read);
var credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// --- Step 4: Write data ---
string range = $"{SheetName}!A1";
var body = new ValueRange { Values = values };
var request = service.Spreadsheets.Values.Update(body, SpreadsheetId, range);
request.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
var response = await request.ExecuteAsync();
Console.WriteLine($"✅ Data written to Google Sheets: {response.UpdatedCells} cells updated.");
}
}