【问题标题】:C# BatchUpdateDocumentRequest ReplaceAllText Google Docs ApiC# BatchUpdateDocumentRequest ReplaceAllText Google Docs API
【发布时间】:2020-02-05 12:39:58
【问题描述】:

我正在尝试更新/替换 Google 文档 模板中的给定文本。

到目前为止我尝试过的代码:

DriveService service = GetDriveService();

var firstname = "Firstname";
var lastname = "Lastname";

BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest();

List<Request> requests = new List<Request>();

var repl = new Request();
var substrMatchCriteria = new SubstringMatchCriteria();
var replaceAlltext = new ReplaceAllTextRequest();
replaceAlltext.ReplaceText = firstname + "." + lastname;
substrMatchCriteria.Text = "vorname.nachname";
replaceAlltext.ContainsText = substrMatchCriteria;
repl.ReplaceAllText = replaceAlltext;

requests.Add(repl);
body.Requests = requests;


//Batch update Request requires 3 Parameters
DocumentsResource.BatchUpdateRequest bUpdate = new DocumentsResource.BatchUpdateRequest(service, body, "160NinGjrmshSga8fWkCFRwApV0FTL1BiJCidH7A1yFw");
bUpdate.Execute(); // The Exception is raised here

DocumentsResource.BatchUpdateRequest需要以下参数:

出现以下错误:

Google.GoogleApiException: "Not Found"

JsonReaderException: Error parsing NaN value. Path '', line 1, position 1.

Diese Ausnahme wurde ursprünglich bei dieser Aufrufliste ausgelöst:
Newtonsoft.Json.JsonTextReader.ParseNumberNaN(Newtonsoft.Json.ReadType, bool)
Newtonsoft.Json.JsonTextReader.ParseValue()
Newtonsoft.Json.JsonTextReader.Read()
Newtonsoft.Json.JsonReader.ReadForType(Newtonsoft.Json.Serialization.JsonContract, bool)
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Newtonsoft.Json.JsonReader, System.Type, bool)
Newtonsoft.Json.JsonSerializer.DeserializeInternal(Newtonsoft.Json.JsonReader, System.Type)
Newtonsoft.Json.JsonConvert.DeserializeObject(string, System.Type, Newtonsoft.Json.JsonSerializerSettings)
Google.Apis.Services.BaseClientService.DeserializeError(System.Net.Http.HttpResponseMessage)

我从文档路径中获取了 documentId

该文件也使用 files.list

我错过了什么/做错了什么?

【问题讨论】:

  • 愿意打赌那不是文件 ID。从 google drive api 执行 files.list 并找到正确的文件 ID。还有什么在 GetDriveService
  • 添加了files.list请求,表示给定的fileId
  • 哪一行在未找到的东西上失败了。
  • 方法 BatchUpdateRequest 只需要两个参数 - 请求和文档​​ ID,请参阅 here 以获取示例。
  • 第三个参数是OPTIONAL字段writeControl。唯一需要的参数是documentIdrequests。我不知道您的变量 service 是什么,但它不太可能是必需的参数之一。我假设它是您想要应用批处理请求的resource。那么它应该类似于 service.BatchUpdateRequest(body, "160NinGjrmshSga8fWkCFRwApV0FTL1BiJCidH7A1yFw"); 我建议您在 C# 实现之前使用 Try it API 测试您的请求

标签: c# google-api google-docs


【解决方案1】:

首先,你可以尝试泛化GetService方法,我这样做是因为我使用了各种范围

public static object GetService(apiType api = apiType.GDrive)
    {
        UserCredential credential;
        
        string CSPath = HostingEnvironment.MapPath("~/MyFolder/");

        using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
        {

            string FolderPath = CSPath;

            string FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(FilePath, true)
                ).Result;

        }
        
        if (api == apiType.GDocs)
        {
            DocsService docsService = new DocsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = MyApplicationName,
            });
            return docsService;
        }
        else
        {
            DriveService driveService = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = MyApplicationName
            });
            return driveService;
        }

    }

那么你可以试试这样的:

public static void EditDoc(string fileId, Dictionary<string, string> textToReplace)
    {
        DocsService service = (DocsService)GetService(apiType.GDocs);
        
        List<Request> requests = new List<Request>();

        foreach (var text in textToReplace)
        {
            var repl = new Request();
            var substrMatchCriteria = new SubstringMatchCriteria();
            var replaceAlltext = new ReplaceAllTextRequest();

            replaceAlltext.ReplaceText = text.Value;
            substrMatchCriteria.Text = text.Key;

            replaceAlltext.ContainsText = substrMatchCriteria;
            repl.ReplaceAllText = replaceAlltext;

            requests.Add(repl);
        }

        BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest { Requests = requests };
        
        service.Documents.BatchUpdate(body, fileId).Execute();

    }

我将此文档用作参考 https://developers.google.com/docs/api/how-tos/merge 出于某种原因 Google 尚未将其翻译成 C#...

【讨论】:

  • 谢谢,这对我有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 2012-05-07
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多