Untitled
unknown
plain_text
2 years ago
3.2 kB
14
Indexable
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using System.Windows.Forms.DataVisualization.Charting;
namespace HopefullyFinal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
string spreadsheetId = "12Qbny7feO2cugT4OKRNSNc-uCuHEJi1DRKqu8dF_VnQ";
IList<IList<object>> data = GetDataFromGoogleSheets(spreadsheetId, "Sheet1");
CreateChart(data, "Sheet1");
}
private IList<IList<object>> GetDataFromGoogleSheets(string spreadsheetId, string range)
{
GoogleCredential credential;
using (var stream = new System.IO.FileStream(@"C:\Users\Ryan\source\repos\HopefullyFinal\HopefullyFinal\dj77p9ki6ulh3cjrblpeg40tt63qr7j6.apps.googleusercontent.com.json", System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(SheetsService.Scope.SpreadsheetsReadonly);
}
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Sheets Graph App"
});
string range = "Sheet1!A1:B5";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute();
return response.Values;
}
private void CreateChart(IList<IList<object>> data, string sheetName)
{
if (data == null || data.Count == 0)
{
// If data is null or empty, exit the method
return;
}
// Create a new chart control
Chart chart = new Chart();
chart.Dock = DockStyle.Top;
chart.Height = 300;
// Create a chart area
ChartArea chartArea = new ChartArea();
chart.ChartAreas.Add(chartArea);
// Create a series
Series series = new Series(sheetName);
series.ChartType = SeriesChartType.Line; // Change chart type as needed
chart.Series.Add(series);
// Add data points to the series
foreach (var row in data)
{
if (row != null && row.Count >= 2)
{
double xValue, yValue;
if (double.TryParse(row[0].ToString(), out xValue) && double.TryParse(row[1].ToString(), out yValue))
{
series.Points.AddXY(xValue, yValue);
}
}
}
// Add the chart to the form
this.Controls.Add(chart);
}
}
}
Editor is loading...
Leave a Comment