如何使用带有C#的Google表格API将CSV文件上传到Google表格?

edwrdkm

我有一种使用restsharp从网站提取CSV的方法。

 class ScheduledBilling
{

    public string Report()
    {
        var client = new RestClient("http://example.com");
        client.CookieContainer = new System.Net.CookieContainer();
        client.Authenticator = new SimpleAuthenticator("username", "xxx", "password", "xxx");
        var request = new RestRequest("/login", Method.POST);


        IRestResponse response = client.Execute(request);


        var ScheduledBilling = client.DownloadData(new RestRequest("/file));
        var csv = System.Text.Encoding.Default.GetString(ScheduledBilling);

        return(csv);

    }

}

总的来说,我一直在使用教程和快速入门,以便可以将信息输入到Google工作表中。

//ScheduledCRMBilling.Report();
            ScheduledCRMBilling obj = new ScheduledCRMBilling();
            string csv = obj.Report();

        String spreadsheetId2 = "xxx";
        String range1 = "Scheduled Billing";

        ValueRange valueRange1 = new ValueRange();   

        valueRange1.MajorDimension = "ROWS";//"ROWS";//COLUMNS

        var oblist1 = new List<object>() { csv };

        SpreadsheetsResource.ValuesResource.UpdateRequest update1 = service.Spreadsheets.Values.Update(valueRange1, spreadsheetId2, range1);

        update1.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;

        UpdateValuesResponse result1 = update1.Execute();

        Console.WriteLine("done!");

我已将范围设置为整个工作表(计划帐单)。发生的情况是,第一个单元格中充满了csv中的所有信息,而不像您将csv导入到Google表格中一样。我应该如何进行?我觉得好像我应该将csv变量作为字符串列表传递,这会将字符串放置在每个单元格中。但是,我不知道何时该换行。

马特·斯坦内特

正如我在OP问题上链接的答案中所提到的,Sheets API不提供上传表格的功能,只能从头开始创建表格。

必须最终使用Drive API,因为它允许上传文件。与本节特别相关的是有关上传google docs类型的部分,因为它们将转换为适当的类型。因此,您的CSV文件将被转换为Google表格。

如果您的电子表格也存储在变量中的内存中,则可以替换以下行:

using (var stream = new System.IO.FileStream("files/report.csv",
                    System.IO.FileMode.Open))

具有以下内容:

using (var stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(csv)))

在调用上载功能之前,您将必须使用本指南为您的应用程序创建凭据,还必须将范围更改为Drive以下是一个我汇总在一起的小应用程序,以演示整个上传流程-假设您已为Drive API创建了OAuth令牌,并将机密下载到了您的项目中。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Text;
using System.Threading;

namespace ConsoleApp3
{
    internal class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        private static string[] Scopes = { DriveService.Scope.Drive };

        private static string ApplicationName = "CsvTest";

        private static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/drive.googleapis.com1.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Sheets API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = "My Report",
                MimeType = "application/vnd.google-apps.spreadsheet"
            };

            var csv = "Heading1,Heading2,Heading3\r\nEntry1,Entry2,Entry3";

            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(csv)))
            {
                request = service.Files.Create(
                    fileMetadata, stream, "text/csv");
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;

            Console.WriteLine("File ID: " + file.Id);

            Console.Read();
        }
    }
}

编辑

您可以更改NameApplication无论您喜欢什么,它们都只是友好名称。

编辑

快乐的编码。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 Python 将 CSV 的文件夹上传到 Google 表格

通过Gspread将.csv上传到Google表格

无法将内容中带有特殊字符的csv作为Google表格上传

如何自动将数据从上传的CSV或XLS文件导入Google表格

如何使用带有react-native-drive-api-wrapper的react native将图像上传到Google驱动器?

将CSV内容转换为Go界面,以将其上传到Google表格

如何使用Google Drive API将文件上传到Google Drive?

如何使用python google drive api将文件夹上传到共享的google drive?

Google表格上传文件-使用/修改响应

如何使用Google Drive API和Python将文件上传到特定文件夹?

如何使用 gdrive 将文件上传到 Google Drive 目录?

如何使用使用Python的驱动器API将文件上传到Google驱动器?

无法将文件上传到Google驱动器-使用C#

使用C#中的HMAC密钥将文件上传到Google Cloud Storage

如何使用JSON API和CloseableHttpClient将文件上传到Google Cloud Storage存储桶?

如何使用uploadType = resumable将文件上传到Google Drive API

将Excel电子表格上传到Google表格

如何替换使用Google表格API下载的CSV文件中的换行符?

通过Google App脚本将CSV / Excel文件作为表格上传

如何使用 Google API 将文件上传到共享文件夹(任何有链接的人都可以完全访问)?

如何使用 Google 表格从另一张带有行的表格中获取值?

使用 Google Apps 脚本将文件上传到 Google Drive

如何使用带有node.js的s3 api将文件上传到Wasabi存储桶?

Google表格:如何将多个文件上传保存在特定文件夹中?

如何使用 Google 应用程序脚本在 Google 表格中导入带有 xml 响应的 txt 文件?

使用Google Apps脚本将文件从Google驱动器上传到外部API

带有 finviz 的 Google 表格

带有IF Google表格的ArrayFormula

如何使用gapi和可恢复的上传将文件上传到Google驱动器?