Files
DiunaBI/WebAPI/Exports/googleSheet.export.cs
Michał Zieliński be8e156ca3 Export excel sheer
2023-08-23 17:30:25 +02:00

57 lines
2.2 KiB
C#

using System.Globalization;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using WebAPI.Models;
using static Google.Apis.Drive.v3.FilesResource;
namespace WebAPI.Exports
{
public class googleSheetExport
{
private GoogleDriveHelper googleDriveHelper;
private SpreadsheetsResource.ValuesResource googleSheetValues;
private readonly IConfiguration configuration;
public googleSheetExport(
GoogleDriveHelper _googleDriveHelper,
SpreadsheetsResource.ValuesResource _googleSheetValues,
IConfiguration _configuration)
{
googleDriveHelper = _googleDriveHelper;
googleSheetValues = _googleSheetValues;
configuration = _configuration;
}
public void export(Layer layer)
{
try
{
List<IList<object>> data = new List<IList<object>>() { new List<object>() { layer.Name!, layer.Number! } };
foreach (Record record in layer.Records!)
{
data.Add(new List<object> { record.Code!, record.Value1! });
}
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = $"{DateTime.Now.ToString(new CultureInfo("pl-PL"))}";
body.MimeType = "application/vnd.google-apps.spreadsheet";
body.Parents = new List<string?> { configuration["exportDirectory"] };
CreateRequest request = googleDriveHelper.Service.Files.Create(body);
var file = request.Execute();
string sheetId = file.Id;
var range = $"Sheet1!A1:B${data.Count}";
ValueRange valueRange = new ValueRange() { Values = data};
var updateRequest = googleSheetValues.Update(valueRange, sheetId, range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
updateRequest.Execute();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}