简体   繁体   English

使用 Google Docs API 复制文档的内容

[英]Copy docs' content using Google Docs API

I need to copy all content between an initial and a final index in Google Docs API in Python , despite if it is text, image, table, etc. I couldn't find any reference about copying contents regardless of the content type using Google Docs API.我需要在 Python 中复制 Google Docs API 中初始和最终索引之间的所有内容,尽管它是文本、图像、表格等。无论使用 Google Docs 的内容类型如何,我都找不到任何关于复制内容的参考API。 Does anyone know how can I implement it?有谁知道我该如何实现它?

For example, suppose I want to duplicate the content below inside a Google Doc by copy and paste:例如,假设我想通过复制和粘贴在 Google Doc 中复制以下内容:

Lorem ipsum dolor sit amet,
[some-image]
[some-table]
consectetur adipiscing elit.

I want to have this output:我想要这个输出:

Lorem ipsum dolor sit amet,
[some-image]
[some-table]
consectetur adipiscing elit.

Lorem ipsum dolor sit amet,
[some-image]
[some-table]
consectetur adipiscing elit.

I have worked with 2 different options to do this:我已经使用了 2 个不同的选项来做到这一点:

Method 1方法一

To copy a complete Google Doc, you can use the files().copy method of Drive API.要复制完整的 Google Doc,您可以使用 Drive API 的files().copy方法。 Something like this:像这样的东西:

copy_title = 'Copy Title'
body = {
    'name': copy_title
}
drive_response = drive_service.files().copy(
    fileId=document_id, body=body).execute()
document_copy_id = drive_response.get('id')

You can review and find a sample code in the answer to this post.您可以查看并在此帖子的答案中找到示例代码。

Note: You can use this method to copy a part of the document by making a complete copy of the file, and after that, edit the new copy of the document while keeping the original one unmodified.注意:您可以使用此方法通过制作文件的完整副本来复制文件的一部分,然后在保持原始文件不变的情况下编辑文件的新副本。 You can use batchUpdate for that您可以为此使用batchUpdate

Method 2方法二

You can use the documents.get method to get the content between an initial and a final index.您可以使用documents.get方法来获取初始索引和最终索引之间的内容。 Something like this :这样的东西:

try:
        service = build('docs', 'v1', credentials=creds)

        # Retrieve the documents contents from the Docs service.
        document = service.documents().get(documentId=DOCUMENT_ID).execute()

Note: If you use the documents.get you will get the raw data of the document.注意:如果您使用documents.get,您将获得文档的原始数据。 You will need to search for the "body" of the document.您将需要搜索文档的“正文” There you will see the content of the document with the parts of the document with their respective initial and a final index.在那里,您将看到文档的内容以及文档的各个部分及其各自的初始索引和最终索引。 After that, you can also use a batchUpdate to paste the information into a new document or the same document as on this case.之后,您还可以使用batchUpdate将信息粘贴到新文档或与本案例相同的文档中。

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM