Export DataSet to GoogleSheet
This commit is contained in:
50
WebAPI/Exports/googleSheet.export.cs
Normal file
50
WebAPI/Exports/googleSheet.export.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
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;
|
||||
public googleSheetExport(GoogleDriveHelper _googleDriveHelper, SpreadsheetsResource.ValuesResource _googleSheetValues)
|
||||
{
|
||||
googleDriveHelper = _googleDriveHelper;
|
||||
googleSheetValues = _googleSheetValues;
|
||||
}
|
||||
public void export(DataSet dataSet)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<IList<object>> data = new List<IList<object>>() { new List<object>() { dataSet.Name, dataSet.Number } };
|
||||
foreach (DataRow dataRow in dataSet.DataRows)
|
||||
{
|
||||
data.Add(new List<object> { dataRow.Code, dataRow.Value });
|
||||
}
|
||||
|
||||
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
|
||||
body.Name = $"export-{DateTime.Now}";
|
||||
body.MimeType = "application/vnd.google-apps.spreadsheet";
|
||||
body.Parents = new List<string> { "1Sar-9ux6GWlXKZiD-l1Mfh1gdsxZif3j" };
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user